Dynamic property name in typescript
Let's say I get data from a search engine in a way like this:
const resultDe = { details_de: "Ein paar Informationen", foo_de:{bar:"barDe"}, code: "1C60" }
const resultEn = { details_en: "Some information", foo_en:{bar:"barEn"} code: "1C60" }
I know the names of the properties but some properties have language dependend suffixes like _de
or _en
. Is there a way to type such data with typescript?
Something like:
type Result = {
`details_${lang}`: string;
}
You can use template literals to create types like this, for example:
type LanguageResult<LangCode extends string> = Record<`details_${LangCode}`, string>;
const enResults: LanguageResult<'en'> = {
details_en: 'test',
};
const enResults: LanguageResult<'de'> = {
details_en: 'test', // <- Error
};
TypeScript Playground
If you don't know what strings you're going to need, you can simply use the widest possible type (i.e. string
itself) to allow any of these codes. For example:
type LanguageResult<LangCode extends string = string> = Record<`details_${LangCode}`, string>;
const anyResults: LanguageResult = {
details_en: 'test',
details_de: 'test',
};
TypeScript Playground
You can use mapped types:
type Lang = 'de' | 'en'
type Result = {
[Property in `details_${Lang}`]: string
}
const result: Result = { details_en: 'foo', details_de: 'bar' }