简体   繁体   English

来自枚举不同类型的 Typescript 接口键

[英]Typescript interface keys from enum different types

I have list of properties that should be as a keys of interfaces with different types.我有一个属性列表,这些属性应该作为不同类型接口的键。 How better to implement them?如何更好地实施它们? I want not to allowed to use properties that not exist in enum.我不想允许使用枚举中不存在的属性。

export enum Properties = {prop1, prop2, prop3}

export interface PropsInterface {
  prop1: Type1;
  prop2: Type2;
  prop3: string;
}


// Usage exanple. 
// I have object of properties. Each of property can be updated separatelly.

let props: PropsInterface = {
   prop1: null,
   prop2: null,
   prop3: null
}

let fieldToUpdate {
   field: Properties = Properties.prop1,
   value: Type1 = 'Some data matching to Type1'
}

props[fieldToUpdate.field] = fieldToUpdate.value;

You should use mapped types :您应该使用映射类型

export enum Properties { prop1, prop2, prop3 }

// type PropsInterface = {
//     0: "any type";
//     1: "any type";
//     2: "any type";
// }
type PropsInterface = {
    [Prop in Properties]: 'any type'
}

Please keep in mind, that enums are numerical by the default,请记住,默认情况下枚举是数字,

You can also use string as enum values:您还可以使用字符串作为枚举值:

export enum Properties { prop1 = 'a', prop2 = 'b', prop3 = 'c' }

// type PropsInterface = {
//     a: "any type";
//     b: "any type";
//     c: "any type";
// }
type PropsInterface = {
    [Prop in Properties]: 'any type'
}

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

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