簡體   English   中英

以 object 為鍵的接口或類型 typescript

[英]Interface or type with object as key in typescript

我有一個帶有一系列值的 object:

const my_enum = {
    value1: 'x-value-1',
    value2: 'x-value-2'

}

我想使用 'x-value-1' 和 'x-value-2' 作為接口或類型的鍵,比如

interface my_interface {
    'x-value-1': string;
    'x-value-2': string;
}

但是,我不想使用我的枚舉來確定鍵,所以我可以在代碼的 rest 上使用它們,如果我想更改我的鍵,我不需要擔心我的字符串地方。 有沒有辦法做類似下面的事情?

interface my_interface {
    `${value1}`: string;
    `${value2}`: string;
}

嘗試這個

const TextType = "Text"; // or "Message" etc
const TitleType = "Title";
const PriorityType = "Priority";

type Notification {
    [TextType]?: string
    [TitleType]?: string
    [PriorityType]?: number
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM