TypeScript$Type-Value-LiteralType

46 阅读1分钟

TypeScript$Type-Value-LiteralType

字面量类型指的是值作为类型。

使用 let 定义的变量具有“通用类型”,使用 const 定义的变量则具有字面量类型:

let changingString = "Hello World"; // string
const constantString = "Hello World"; // 'Hello World'
let x: "hello" = "hello";
// OK
x = "hello";
// ...
x = "howdy";
// error. Type '"howdy"' is not assignable to type '"hello"'.

Unions:| 可以把多个字面量类型组合成一个“集合”:

function printText(s: string, alignment: "left" | "right" | "center") {
  // ...
}
printText("Hello, world", "left");
printText("G'day, mate", "centre");
// error. Argument of type '"centre"' is not assignable to parameter of type '"left" | "right" | "center"'.
function compare(a: string, b: string): -1 | 0 | 1 {
  return a === b ? 0 : a > b ? 1 : -1;
}

Literal Inference

对于对象,通过 as const,可以把一个对象的属性变为 readonly;同时,属性的类型也变成了字面量。对于基本类型,as const 可以把它的类型变为字面量类型。

通过 as "GET" 可以把一个值的类型固定为字面量类型 "GET"

declare function handleRequest(url: string, method: "GET" | "POST"): void;
 
const req = { url: "https://example.com", method: "GET" };
handleRequest(req.url, req.method);
// error. Argument of type 'string' is not assignable to parameter of type '"GET" | "POST"'.
// Change 1.1:
const req = { url: "https://example.com", method: "GET" as "GET" };
// change 1.2:
const req = { url: "https://example.com", method: "GET" } as const;
handleRequest(req.url, req.method);
// Change 2:
handleRequest(req.url, req.method as "GET");