Home > Blockchain >  Interface or type with object as key in typescript
Interface or type with object as key in typescript

Time:03-22

I have an object with a series of values:

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

}

I want to use 'x-value-1' and 'x-value-2' as the keys of a interface or a type, something like

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

However, I don't want to use my enum to determine the keys, so I can use them on the rest of the code, and if I ever want to change my keys I don't need to worry about my strings all over the place. Is there a way to do something like the following?

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

CodePudding user response:

try this

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

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

  • Related