简体   繁体   English

有没有办法在 TypeScript 定义中动态生成成员?

[英]Is there a way to dynamically generate members in a TypeScript definition?

I don't think the title for this question is very good, but I had trouble coming up with something better, so it'll do for now.我不认为这个问题的标题很好,但我很难想出更好的东西,所以现在就可以了。

I'm also fairly sure that what I want isn't supported, but I'd love to be proved wrong!我也相当确定我想要的东西不被支持,但我很想被证明是错误的!

I have an API I'm calling, and it varies the member names in the object returned based on the query.我有一个正在调用的 API,它根据查询改变返回的对象中的成员名称。

eg例如

GetInfo(languages?:string[]);
GetInfo() => { name: "Cologne" };
GetInfo(["en", "de"]) => { name: "Cologne", name_en: "Cologne", name_de: "Köln" };

Is there a way to create a definition that will "generate" the name_{language} members?有没有办法创建一个定义来“生成” name_{language} 成员?

There is no support for manipulation of property names in this way (ie. concatenate a string to another string and have this be a type checked property).不支持以这种方式操作属性名称(即将一个字符串连接到另一个字符串并使其成为类型检查属性)。

The best you can do is not just return an object with the properties being the same name as the language names:您能做的最好的事情不仅仅是返回一个属性与语言名称同名的对象:

function GetInfo<T extends string>(langs: T[]): Record<T | 'default', string>{
  return null as any;
}
let values = GetInfo(["en", "de"]) // values is  { en: string; de: string; default: string  }
values.default
values.de
values.en

There is an issue on GitHub that suggest adding support for string literal manipulations, but it's nowhere on the roadmap for now GitHub 上有一个问题建议添加对字符串文字操作的支持,但目前在路线图上还没有

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

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