Const Assertion
一句话解释
const assertion (as const) tells TypeScript 到 infer narrowest 可能类型 — literal 类型相反的 widened 基础类型, and readonly 数组/tuples.
用大白话说
const assertion (as const) tells TypeScript 到 use 大多数特定类型可能. 它 prevents 类型 widening: 5 stays 5 相反的 becoming number, and arrays become readonly tuples.
For example, const colors = ["red", "green"] as const gives colors the type readonly ["red", "green"] — a readonly tuple with literal string types. Without as const, it would be string[].
Const assertions are useful for exhaustiveness checking, defining constant maps, and creating immutable configurations. They work on object literals, arrays, and expressions. They are a compile-time operation with no runtime effect.
示例
const status = "active" as const; // type: "active" (not string)
const directions = ["N", "S", "E", "W"] as const; // type: readonly ["N", "S", "E", "W"]
const config = { port: 3000 } as const; // type: { readonly port: 3000 }as const prevents widening: 字符串 stay literal, 数组 become readonly tuples.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。