我最初定义了DOMRectReadOnly和StyleProperties类型的the intersection type,如下所示,结果类型为"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关键字的用法有什么问题?
发布于 2021-02-07 00:06:19
您使用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应该可以做你想做的事情!
https://stackoverflow.com/questions/66078701
复制相似问题