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:
- To access a key inside an interface you can use square bracket notation:
interface ITest {
colorVariant: 'default' | 'primary' | 'secondary'
}
type ColorVariant = ITest["colorVariant"]
- 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.
- 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.