TYPESCRIPT 快速参考
类型、接口、泛型、工具类型
基本类型
原始类型
let name: string = "Alice";
let age: number = 25;
let active: boolean = true;
let data: null = null;
let x: undefined = undefined;
特殊类型
| any | 跳过类型检查 |
| unknown | 类型安全的 any(使用前必须收窄) |
| void | 无返回值 |
| never | 函数永不返回(抛出异常或无限循环) |
| object | 任何非原始类型 |
数组与元组
数组
let nums: number[] = [1, 2, 3];
let names: Array = ["a", "b"];
let matrix: number[][] = [[1, 2], [3, 4]];
元组
let pair: [string, number] = ["age", 25];
let rgb: [number, number, number] = [255, 0, 0];
// Named tuples (labels for readability)
type Point = [x: number, y: number];
接口
定义与使用
interface User {
name: string;
age: number;
email?: string; // optional
readonly id: number; // immutable
}
const user: User = { name: "Alice", age: 25, id: 1 };
继承接口
interface Employee extends User {
role: string;
department: string;
}
索引签名
interface StringMap {
[key: string]: string;
}
const env: StringMap = { NODE_ENV: "prod" };
类型别名
type ID = string | number;
type Point = { x: number; y: number };
type Callback = (data: string) => void;
interface vs type
| interface | 支持 extends 扩展和声明合并 |
| type | 联合类型、交叉类型、映射类型、元组 |
联合与交叉类型
联合类型
type Status = "loading" | "success" | "error";
type ID = string | number;
function print(val: string | number) {
if (typeof val === "string") {
console.log(val.toUpperCase());
}
}
交叉类型
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
// Person has both name and age
可辨别联合
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rect"; w: number; h: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.radius ** 2;
case "rect": return s.w * s.h;
}
}
函数
参数与返回值类型
function add(a: number, b: number): number {
return a + b;
}
// Arrow function
const greet = (name: string): string =>
`Hello, ${name}!`;
// Optional & default params
function log(msg: string, level?: string): void {}
function log(msg: string, level = "info"): void {}
函数重载
function parse(input: string): number;
function parse(input: number): string;
function parse(input: string | number) {
return typeof input === "string"
? parseInt(input)
: input.toString();
}
剩余参数
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
泛型
泛型函数
function identity(value: T): T {
return value;
}
identity("hello"); // explicit
identity(42); // inferred: number
泛型接口与约束
interface Box {
value: T;
}
const box: Box = { value: 42 };
// Constraints
function getLen(
item: T
): number {
return item.length;
}
枚举
enum Direction { Up, Down, Left, Right }
let d: Direction = Direction.Up; // 0
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
}
let s: Status = Status.Active; // "ACTIVE"
// const enum (inlined at compile time)
const enum Color { Red, Green, Blue }
类型守卫
内置守卫
// typeof
if (typeof x === "string") { /* x: string */ }
// instanceof
if (err instanceof Error) { /* err: Error */ }
// in
if ("name" in obj) { /* obj has name */ }
自定义类型守卫
function isString(val: unknown): val is string {
return typeof val === "string";
}
if (isString(input)) {
input.toUpperCase(); // narrowed to string
}
断言函数
function assertDefined(
val: T | null
): asserts val is T {
if (val === null) throw new Error("null");
}
工具类型
| Partial<T> | 所有属性变为可选 |
| Required<T> | 所有属性变为必填 |
| Readonly<T> | 所有属性变为只读 |
| Pick<T, K> | 从 T 中选取属性 K |
| Omit<T, K> | 从 T 中移除属性 K |
| Record<K, V> | 键为 K、值为 V 的对象类型 |
| Exclude<T, U> | T 中不在 U 中的类型 |
| Extract<T, U> | T 中也在 U 中的类型 |
| NonNullable<T> | 从 T 中排除 null 和 undefined |
| ReturnType<T> | 函数 T 的返回值类型 |
| Parameters<T> | 函数 T 的参数类型 |
| Awaited<T> | 展开 Promise 类型 |
工具类型示例
interface User { name: string; age: number; email: string }
type UserPreview = Pick;
type UserUpdate = Partial;
type UserMap = Record;
type CreateUser = Omit;