[TypeScript] Statically Type String Literals with Template Literal Types in TypeScript

In this lesson, we're going to explore template literal types, another powerful feature of TypeScript's type system. Template literal types have the same syntax as template literals in JavaScript, but they're used in type positions. Using template literal types, we can produce a union of string literal types and perform string concatenation in the type space:

type Dimension = "block" | "inline";
type MarginProperty = `margin-${Dimension}`;
type MarginProperty =
  | "margin-block-start"
  | "margin-block-end"
  | "margin-inline-start"
  | "margin-inline-end";

type MarginUnit = "px" | "vh" | "vw";
type MarginValue = `${number}${MarginUnit}`;
type MarginDeclaration = [MarginProperty, MarginValue];

const margin: MarginDeclaration = ["margin-block-start", "20vh"];

 

posted @ 2021-05-11 16:55  Zhentiw  阅读(69)  评论(0编辑  收藏  举报