[英]Typescript: 'keyof typeof value' makes different type result compared to 'keyof interface'
I initially defined the intersection type of type DOMRectReadOnly
and StyleProperties
like below which results type "size" | "start" | "end"
我最初定义了类型DOMRectReadOnly
和StyleProperties
的交集类型,如下所示,结果类型为"size" | "start" | "end"
"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];
But I want to remove interface StyleProperties
part and replace its uses with typeof StyleProperties
like below, but it results type never
.但是我想删除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];
What's wrong in my usage of typeof
keyword?我使用typeof
关键字有什么问题?
Nothing is wrong with your use of typeof
.您使用typeof
没有任何问题。 The issue is that the types that typescript is able to infer for StyleProperties
is less strict than you'd like:问题是 typescript 能够为StyleProperties
推断的类型没有您想要的那么严格:
const StyleProperties = {
size: ["width", "height"],
start: ["left", "top"],
end: ["right", "bottom"]
};
type Example = typeof StyleProperties;
If you look at this, you'll see that these properties are now string[]
rather than typed tuples.如果你看这个,你会发现这些属性现在是string[]
而不是类型化的元组。 If you tell typescript that these are constants and won't change, you should get the type you want:如果你告诉 typescript 这些是常量并且不会改变,你应该得到你想要的类型:
const StyleProperties = {
size: ["width", "height"] as const,
start: ["left", "top"] as const,
end: ["right", "bottom"] as const,
};
type Example = typeof StyleProperties;
And with the correct type, using typeof
should do what you want!并且使用正确的类型,使用typeof
应该可以满足您的要求!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.