首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“keyof typeof value”与“keyof interface”产生不同的类型结果

“keyof typeof value”与“keyof interface”产生不同的类型结果
EN

Stack Overflow用户
提问于 2021-02-06 23:43:14
回答 1查看 36关注 0票数 0

我最初定义了DOMRectReadOnlyStyleProperties类型的the intersection type,如下所示,结果类型为"size" | "start" | "end"

代码语言:javascript
复制
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

代码语言:javascript
复制
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关键字的用法有什么问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-07 00:06:19

您使用typeof没有任何问题。问题是typescript能够为StyleProperties推断的类型并不像你想的那样严格:

代码语言:javascript
复制
const StyleProperties = {
    size: ["width", "height"],
    start: ["left", "top"],
    end: ["right", "bottom"]
};
type Example = typeof StyleProperties;

如果您看一下这里,您将看到这些属性现在是string[]而不是类型化的元组。如果你告诉typescript这些是常量并且不会改变,你应该得到你想要的类型:

代码语言:javascript
复制
const StyleProperties = {
    size: ["width", "height"] as const,
    start: ["left", "top"] as const,
    end: ["right", "bottom"] as const,
};
type Example = typeof StyleProperties;

有了正确的类型,使用typeof应该可以做你想做的事情!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66078701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档