[英]Typescript: 'keyof typeof value' makes different type result compared to 'keyof interface'
我最初定义了类型DOMRectReadOnly
和StyleProperties
的交集类型,如下所示,结果类型为"size" | "start" | "end"
"size" | "start" | "end"
"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
替换它的用途,如下所示,但它导致 type 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
应该可以满足您的要求!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.