繁体   English   中英

如何在 TypeScript 中使用动态键定义 object 类型?

[英]How to define an object type with dynamic keys in TypeScript?

我有一个 const object 看起来像这样:

export const Language: Values = {
  es: {urlValue: 'es', label: 'Spain'},
  en: {urlValue: 'en', label: 'Anything'},
  eb: {urlValue: 'eb', label: 'Other thing'},
};

export interface Values {
  [name: string]: Value;
}

export interface Value {
  urlValue;
  label;
  selected?;
}

现在在应用程序的某个地方,我们读取了一些具有这种格式的数据,它们恰好具有完全相同的键:

{
  es: 32,
  en: 11,
  eb: 56
}

所以实际上我需要另一个 object 类型,如下所示:

export class AnotherObject {

  constructor(public es: number,
              public en: number,
              public eb: number) {
  }
}

但是我可以动态创建这种类型,以便它自动使用语言 object 的键或“值”类型的 urlValue 吗?

PS:问题是我们确切用例的简化形式,其中我们有多个常量,如语言。 因此,自动化将非常有帮助。

编辑:对于@basarat 的建议-由于此 object 是父 object 的一部分,因此我实际上需要在此部分中定义类型:

export class ParentObject {
  thatObjectAbove: AnotherObject;
  otherObjects: ..
  ..
}

export interface AnotherObject {
  [name: LanguageOptions]: number;
}

我有错误“索引签名参数类型不能是联合类型。请考虑改用映射的 object 类型。” 在“[名称:LanguageOptions]:数字;”行的“名称”部分

keyof类型运算符为您提供作为类型的键名:

export const Language = {
  es: {urlValue: 'es', label: 'Spain'},
  en: {urlValue: 'en', label: 'Anything'},
  eb: {urlValue: 'eb', label: 'Other thing'},
};

type LanguageOptions = keyof typeof Language; // 'es' | 'en' | 'eb'

你可能会改变你的代码吗?

class DynamicClass<T> {
    constructor(values?: { [key in keyof T]?: T[key] }) {
        for (const key of Object.keys(values)) {
            this[key] = values[key];
        }
    }
}

class MyClass extends DynamicClass<MyClass> {
    attr1: string;
    attB: number;
    obj: {
        wow: string,
        yeah: boolean
    };
}


new MyClass({
    attr1: 'a',
    obj: {
        wow: '',
        yeah: true
    },
    att
})

在此处输入图像描述

继续这个答案

我已经实现了将 AnotherObject 定义为类型而不是接口的目标。

type LanguageOptions = keyof typeof Language;  // as from basarat's answer

type AnotherObject = {[key in LanguageOptions]: number}; // is actually a type, still is named as 'object' so that it is still compatible with the question's code
    
export class ParentObject {
  thatObjectAbove: AnotherObject;
  otherObjects: ..
  ..
}

正如这里所说,这是因为 typescript 的奇怪行为,可以通过这种方式修复。

因此,单线的最终解决方案:

thatObjectAbove: {[key in keyof typeof Language]: number};

或者

thatObjectAbove: Record<keyof typeof Language, number>;  // Record is a built-in typescript type

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM