简体   繁体   English

typescript 中的动态属性名称

[英]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 .我知道属性的名称,但有些属性具有语言相关的后缀,例如_de_en Is there a way to type such data with typescript?有没有办法用 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 TypeScript 游乐场


If you don't know what strings you're going to need, you can simply use the widest possible type (ie string itself) to allow any of these codes.如果你不知道你需要什么字符串,你可以简单地使用最广泛的类型(即string本身)来允许这些代码中的任何一个。 For example:例如:

type LanguageResult<LangCode extends string = string> = Record<`details_${LangCode}`, string>;

const anyResults: LanguageResult = {
  details_en: 'test',
  details_de: 'test',
};

TypeScript Playground TypeScript 游乐场

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' }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM