Home > Back-end >  Is it possible to set TypeScript interface key using method
Is it possible to set TypeScript interface key using method

Time:10-15

I have an interface let's say:

interface SampleInterface {
    [key: string]: string;
}

Usually we would define a constant as:

const sampleConstant: SampleInterface = {
    key: 'value'
}

Why can't I do

const sampleConstantWithMethod: SampleInterface = {
    someMethod(): 'value'
}


function someMethod(): string {
    return 'key'
}

Is there some work around to this, while still using an Interface?

CodePudding user response:

Sounds like you're looking for a computed property, which is indicated by wrapping the key expression in square brackets like so:

const sampleConstantWithMethod: SampleInterface = {
    [someMethod()]: 'value' // okay
}

Playground link to code

  • Related