与"键接口"相比,"键类型值"产生不同的类型结果

  • 本文关键字:类型 结果 相比 接口 typescript
  • 更新时间 :
  • 英文 :


我最初定义了类型DOMRectReadOnlyStyleProperties的交集类型,如下所示,结果类型"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应该做你想要的!

最新更新