Home > Enterprise >  Typing an object key with same variants of an interface attribute
Typing an object key with same variants of an interface attribute

Time:09-07

How can I turn an interface attribute variants in required exact object keys?

Something like this:

interface ITest {
    colorVariant: 'default' | 'primary' | 'secondary'
}

//Correct
const colorVariantList: Pick<ITest, 'colorVariant'> = {
    default: 'test'
    primary: 'test2',
    secondary: 'test3',
}

//Error
const colorVariantList: Pick<ITest, 'colorVariant'> = {
    default: 'test'
    primary: 'test2',
}

//Error
const colorVariantList: Pick<ITest, 'colorVariant'> = {
    default: 'test'
    primary: 'test2',
    potato: 'test3',
}

CodePudding user response:

  1. To access a key inside an interface you can use square bracket notation:
interface ITest {
    colorVariant: 'default' | 'primary' | 'secondary'
}

type ColorVariant = ITest["colorVariant"]
  1. To define an object with keys equal to the values of a union type, you can use a Record:
type ColorVariant = 'default' | 'primary' | 'secondary'

const colorVariantList: Record<ColorVariant, string> = {
    default: 'test',
    primary: 'test2',
    secondary: 'test3',
}

In the example above, the object is defined as a mapping from each of the values in the ColorVariant union type to a string.

  1. Combining the two ideas together:
const colorVariantList: Record<ITest["colorVariant"], string> = {
    default: 'test',
    primary: 'test2',
    secondary: 'test3',
}

See the typescript playground for a full example.

  • Related