Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Interface or type with object as key in typescript

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

try this

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading