类型推断与类型断言
约 484 字大约 2 分钟
布欧-Lewyon
2026-05-16
首页 › TypeScript › 基础入门 › 类型推断与类型断言
类型推断
TS 能自动推断类型,不需要显式注解:
let count = 0; // 推断为 number
let name = '张三'; // 推断为 string
// 函数返回值自动推断
function add(a: number, b: number) {
return a + b; // 推断返回类型为 number
}
// 上下文类型(根据赋值推断)
const arr = [1, 2, 3].map(x => x * 2); // number[]const 断言
// 普通推断:string 类型
let a = 'hello'; // string
// const 声明:字面量类型
const b = 'hello'; // "hello"(字面量类型)
// as const:深度只读 + 字面量
const config = {
server: 'prod',
port: 8080,
} as const;
// config.server 的类型是 "prod"(字面量),而非 string
// config.port 的类型是 8080(字面量),而非 number
// 数组 as const
const roles = ['admin', 'user', 'guest'] as const;
// 类型:readonly ["admin", "user", "guest"]类型断言
当你比 TS 更了解值的类型时,使用类型断言:
// as 语法(推荐)
const input = document.getElementById('app') as HTMLInputElement;
// const el = document.getElementById('input')!; // 非空断言
// 双重断言(慎用)
const value = 'hello' as unknown as number;
// 非空断言 !
function process(id?: string) {
return id!.toUpperCase(); // 告诉 TS id 一定存在
}satisfies 操作符
satisfies(TS 4.9+,5.3 完善)用于保留推导类型的同时做约束检查:
type Color = 'red' | 'blue' | 'green';
const palette = {
primary: 'red',
secondary: 'blue',
tertiary: 'green',
} satisfies Record<string, Color>;
// palette.primary 的类型是 "red"(字面量),而非 Color
// 但如果赋值为 'yellow' 会报错(不在 Color 中)与
: Color注解的区别:satisfies不改变推断类型,只做约束检查。
小结
| 概念 | 说明 |
|---|---|
| 类型推断 | TS 自动推导类型 |
as const | 深度只读 + 字面量类型 |
as 断言 | 开发者告知 TS 确切类型 |
! 非空断言 | 断言值不为 null/undefined |
satisfies | 检查约束,保留精确类型 |
