John Smith
John Smith

Reputation: 4353

Typescript - string concatenation as type

Is it possible to do some rudimentary string manipulations, as you're converting literal unions to type names?

Example:

type Strings = "Fork" | "Spoon";

type GetMethods = { // I want this to be automatically generated basing on Strings
   getFork: Function,
   getSpoon: Function
}

Upvotes: 1

Views: 1402

Answers (1)

spender
spender

Reputation: 120400

In TypeScript v.4.1, (which looks like it will be released in less than 2 weeks time) you can use Template Literal Types to do this really easily:

type Strings = "Fork" | "Spoon";

type FuncNames = `get${Strings}`;

type GetMethods = { [K in FuncNames]: Function }

Playground link

Prior to TS4.1, it doesn't look like this is possible.

Upvotes: 2

Related Questions