简体   繁体   中英

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.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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