[Typescript v4.1] Template type literals

type Corner = `${'top' | 'bottom'}-${ 'left' | 'right'}`

type VerticalAlignment = "top" | "middle" | "bottom";
type HorizontalAlignment = "left" | "center" | "right";

// Takes
//   | "top-left"    | "top-center"    | "top-right"
//   | "middle-left" | "middle-center" | "middle-right"
//   | "bottom-left" | "bottom-center" | "bottom-right"
declare function setAlignment(value: `${VerticalAlignment}-${HorizontalAlignment}`): void;

setAlignment("top-left");   // works!
setAlignment("top-middel"); // error!
setAlignment("top-pot");    // error! but good doughnuts if you're ever in Seattle

https://devblogs.microsoft.com/typescript/announcing-typescript-4-1-beta/#template-literal-types

原文地址:https://www.cnblogs.com/Answer1215/p/13982735.html