打字稿:“keyof typeof value”与“keyof interface”相比产生不同的类型结果

时间:2021-02-06 15:43:14

标签: typescript

我最初定义了 DOMRectReadOnly 类型的 the intersection typeStyleProperties 类型,如下所示,结果类型为 "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 关键字有什么问题?

1 个答案:

答案 0 :(得分:1)

您对 typeof 的使用没有任何问题。问题是 typescript 能够为 StyleProperties 推断的类型没有您想要的那么严格:

const StyleProperties = {
    size: ["width", "height"],
    start: ["left", "top"],
    end: ["right", "bottom"]
};
type Example = typeof StyleProperties;

如果你看这个,你会发现这些属性现在是 string[] 而不是类型化的元组。如果你告诉打字稿这些是常量并且不会改变,你应该得到你想要的类型:

const StyleProperties = {
    size: ["width", "height"] as const,
    start: ["left", "top"] as const,
    end: ["right", "bottom"] as const,
};
type Example = typeof StyleProperties;

使用正确的类型,使用 typeof 应该可以满足您的需求!