我最初定义了类型DOMRectReadOnly
和StyleProperties
的交集类型,如下所示,结果类型"size" | "start" | "end"
。
interface StyleProperties {
size: ["width", "height"];
start: ["left", "top"],
end: ["right", "bottom"];
}
export const StyleProperties: StyleProperties = {
size: ["width", "height"],
start: ["left", "top"],
end: ["right", "bottom"]
};
type DOMRectStyleProperties = {
[P in keyof StyleProperties]:
(StyleProperties[P][0] | StyleProperties[P][1]) extends keyof DOMRectReadOnly
? P
: never
}[keyof StyleProperties];
但是我想删除interface StyleProperties
部分,用typeof StyleProperties
代替它的用途,像下面这样,但它的结果类型是never
。
export const StyleProperties = {
size: ["width", "height"],
start: ["left", "top"],
end: ["right", "bottom"]
};
type DOMRectStyleProperties = {
[P in keyof typeof StyleProperties]:
(typeof StyleProperties[P][0] | typeof StyleProperties[P][1]) extends keyof DOMRectReadOnly
? P
: never
}[keyof typeof StyleProperties];
我使用typeof
关键字有什么问题?
您使用typeof
没有任何问题。问题是typescript能够为StyleProperties
推断的类型没有您希望的那么严格:
const StyleProperties = {
size: ["width", "height"],
start: ["left", "top"],
end: ["right", "bottom"]
};
type Example = typeof StyleProperties;
如果你看一下这个,你会发现这些属性现在是string[]
而不是类型化元组。如果你告诉typescript这些都是常量,不会改变,你应该得到你想要的类型:
const StyleProperties = {
size: ["width", "height"] as const,
start: ["left", "top"] as const,
end: ["right", "bottom"] as const,
};
type Example = typeof StyleProperties;
和正确的类型,使用typeof
应该做你想要的!