Home > other >  Typescript prepended union template literal types
Typescript prepended union template literal types

Time:07-11

I there a way to create literal string types from other string types with a prefix? Beter knowing there isn't than dwendle on this idea.

type UserField = "id" | "name";
type PostField = "id" | "message" | ("author."   UserField); // Something like this?
let somePostFields: PostField[] = ["id", "message", "author.name"];

CodePudding user response:

You can use the feature template literal types using string interpolation allowing union types to combine.

type UserField = "id" | "name";
type PostField = "id" | "message" | `author.${UserField}`; 
  • Related