TypeScript type 别名
为联合、对象、元组、函数与泛型结构命名,区分结构复用、接口合并及运行时值。
学完这一章,你能够
- 复用别名而不引入名义身份
- 分别定义元组、函数、泛型和映射别名
- 选择接口合并或封闭别名
名字帮助阅读,不创造运行时品牌
type ID = string | number为一个类型表达式起名。ID与该联合按结构兼容,别名不会生成构造函数,不能用new ID或把ID当运行时校验器。两个同形别名也不会因为名字不同就自动隔离用户ID与订单ID。
type ID = string | number;
type Point = { x: number; y: number };
const id: ID = "mbsky-1";
const point: Point = { x: 10, y: 20 };类型语法在生成JavaScript时被擦除;若需要在接口边界判断输入,仍要写校验逻辑。常用结构才值得命名,给每一个string都增加无含义别名会降低可读性。
接口和对象别名可以表达相同结构
type Writer = { name: string; age: number };
interface Reviewer { name: string; age: number }
const writer: Writer = { name: "蓝色天空", age: 25 };
const reviewer: Reviewer = writer;interface可以通过同名声明合并;同一作用域的type不能重复声明。type还可以表示原始值、联合、元组和函数。类能implements一个成员已知的对象别名,不是只有接口能被实现;不能直接implements一个联合类型。两者的对象兼容仍是结构化判断。
状态和结果分别限制可能值
type Status = "pending" | "success" | "error";
type Output = string | number | boolean;
function display(status: Status): string { return `状态:${status}`; }这些集合只在类型检查期间限制赋值。成功数据与错误消息之间若有依赖,不宜只写success:boolean、data?、error?三个互相独立的字段:那种结构允许成功却没有数据。可辨识联合可以把条件表达得更准确。
type Result<T> = { success: true; data: T } | { success: false; error: string };
type Pair<K, V> = { key: K; value: V };核心实例把两种Result值传给resultLabel函数,让函数参数保留完整联合后再收窄。若在固定success:true的const旁直接读取错误分支,控制流已经排除了失败分支,该分支会是never;不能用断言掩盖这种诊断。成功与失败两次调用分别演示data和error。
位置和调用签名也能复用
type Coordinate = [number, number];
type NameAge = [string, number];
type Callback = (result: string) => void;
type Operation = (a: number, b: number) => number;
const add: Operation = (a, b) => a + b;
const multiply: Operation = (a, b) => a * b;元组约束每个位置的类型与声明长度;需要防止push等修改时可用readonly元组。函数别名约束参数和返回关系,void返回类型表示调用方不使用返回值,不表示所有实现都禁止返回值。
泛型别名与映射别名
type View<T> = { readonly [K in keyof T]: T[K] };
type Patch<T> = { [K in keyof T]?: T[K] };
interface Profile { name: string; age: number }
const view: View<Profile> = { name: "蓝色天空网", age: 25 };
const patch: Patch<Profile> = { name: "学习站" };Readonly和Partial已是标准库工具名;自定义实现放模块内也应使用能区分用途的名称。只读与可选映射默认是浅层:嵌套对象成员不会因此全部冻结,映射也不会拷贝、过滤或修改实际对象。
完整核心源码与验证目标
export {};
type ID = string | number;
type Coordinate = readonly [number, number];
type Operation = (a: number, b: number) => number;
type Result<T> = { success: true; data: T } | { success: false; error: string };
type Pair<K,V> = { key: K; value: V };
type View<T> = { readonly [K in keyof T]: T[K] };
type Patch<T> = { [K in keyof T]?: T[K] };
const id: ID = "mbsky-1";
const point: Coordinate = [10,20];
const add: Operation = (a,b) => a+b;
const result: Result<string> = {success:true,data:"蓝色天空网"};
const pair: Pair<string,number> = {key:"age",value:25};
const original: View<{name:string;age:number}> = {name:"蓝色天空网",age:25};
const patch: Patch<typeof original> = {name:"学习站"};
function resultLabel(value:Result<string>):string{return value.success?value.data:value.error;}
console.log(id,point.join(","),add(2,3));
console.log(resultLabel(result));
console.log(resultLabel({success:false,error:"教学失败"}));
console.log(JSON.stringify(pair),JSON.stringify(patch));
所需环境:固定版本的TypeScript编译器,启用strict;编译产物在支持ES2022的JavaScript环境中运行
当前源码 SHA256:c72c829bf68ccc30b10b7e950d5d580be82a09b500a1548b935f0d9dc84c7a24
- mbsky-1 10,20 5
- 蓝色天空网
- 教学失败
- 最后输出age/25键值对与只含name的补丁;类型别名没有额外运行时构造器
常见错误与边界
- 把别名当不同的名义类型
- 重复定义type期待合并
- 自定义全局Readonly与标准库冲突
- 把只读映射当深冻结
练习与解答
给Result<number>分别构造成功与失败值,解释为什么成功分支必须有data。
展开参考解答
使用{success:true,data:100}或{success:false,error:"原因"};判别字段为true时只剩含data的分支。