簡體   English   中英

來自枚舉不同類型的 Typescript 接口鍵

[英]Typescript interface keys from enum different types

我有一個屬性列表,這些屬性應該作為不同類型接口的鍵。 如何更好地實施它們? 我不想允許使用枚舉中不存在的屬性。

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;

您應該使用映射類型

export enum Properties { prop1, prop2, prop3 }

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

請記住,默認情況下枚舉是數字,

您還可以使用字符串作為枚舉值:

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