【问题标题】:How to use generics to be keys of enum如何使用泛型作为枚举的键
【发布时间】:2020-12-05 16:22:46
【问题描述】:

我正在尝试创建一个通用方法来设置 Web 组件属性。我决定将我所有的ObservedAttributes web-component 放在 enum 中,然后使用这个 enum 的键来设置 web-component 属性,但是我不知道如何为 keysObject 定义一个类型/strong> 将是 enums keys,值将是 string

假设我有这个枚举:

TextFieldObservedAttributes {
    PLACEHOLDER = 'placeholder',
    LABEL = 'label',
    SIZE = 'size'
}

基于这个枚举,我想要这种类型:

type EnumKeyStringValue = Record<'PLACEHOLDER' | 'LABEL' | 'SIZE', string>;
const example: EnumKeyStringValue = {
  PLACEHOLDER: 'text',
  LABEL: 'text',
  SIZE: 'test'
}

这可行,但我不知道如何使用泛型来实现这一点。我尝试了类似的方法:

protected initialize<T>(props: Record<keyof typeof T, string>): void {
    for (const [key, value] of Object.entries(props)) {
        this.setAttribute(key.toLowerCase(), value);
    }
}

但是由于这些错误,这不起作用:

'T' 被声明,但它的值从未被读取。

'T' 仅指一种类型,但在这里用作值。

如何定义这样的泛型类型?

【问题讨论】:

  • 您会收到错误消息,因为范围内没有名为 T 的值。 typeof 在类型位置返回值的类型。为什么不T extends Record&lt;string, string&gt;(props: T) &lt;K extends string&gt;(props: Record&lt;K, string&gt;)
  • @AluanHaddad 第一个选项对我不起作用,因为我没有提示,但您的第二个提议让我这样做:type KKWebComponentProps&lt;T extends string&gt; = Partial&lt;Record&lt;T, string&gt;&gt; 这正是我想要的。请将第二个命题添加到答案部分

标签: typescript generics types enums


【解决方案1】:

根据 cmets 部分的@Aluan Haddad 建议,我想出了这个解决方案:

type EnumKeysNames<T extends string> = Partial<Record<T, string>>;

然后我可以这样使用这种类型:

function test(props: EnumKeysNames<SomeEnum>): void {
  //...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多