[英]How to type a string as an Object property-key in a typescript Object interface?
[英]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.