Type Template Literals

Start with this sandbox.

Initial State

type CharacterClass = "warror" | "paladin" | "wizard" | "cleric";

type LawChaos = "lawful" | "neutral" | "chaotic";
type GoodEvil = "good" | "neutral" | "evil";

type Character = {
  name: string;
  profession: CharacterClass;
  alignment: string; // We want to chage this!
};

const steve: Character = {
  name: "Steve",
  profession: "wizard",
  alignment: "chaotic-good",
};

Solution

type CharacterClass = "warror" | "paladin" | "wizard" | "cleric";

type LawChaos = "lawful" | "neutral" | "chaotic";
type GoodEvil = "good" | "neutral" | "evil";

type Alignment = `${LawChaos}-${GoodEvil}`;

type Character = {
  name: string;
  profession: CharacterClass;
  alignment: Alignment;
};

const steve: Character = {
  name: "Steve",
  profession: "wizard",
  alignment: "chaotic-good",
};

Your Turn

Visit this sandbox.

Make a template literal type that eventually breaks the second two examples.

type VerticalAlignment = "top" | "center" | "bottom";
type HorizonalAlignment = "left" | "center" | "right";

type Box = {
  x: number;
  y: number;
  alignment: string; // Let's make this better.
};

const a: Box = {
  x: 10,
  y: 10,
  alignment: "top-center",
};

const b: Box = {
  x: 20,
  y: 20,
  alignment: "bottom-right",
};

const shouldBreak: Box = {
  x: 20,
  y: 20,
  alignment: "left-right",
};

const shouldBreakAtFirstButEventuallyWork: Box = {
  x: 100,
  y: 100,
  alignment: "center",
};

Extension

  • Could we get 'center' to work instead of 'center-center'?
  • And what if we wanted to get rid of 'center-center'?

Solutions