跳到主要内容

基础类型与数据结构

TypeScript 在 JavaScript 值的基础上添加静态类型。下面按原始值、数组、对象和集合介绍常用写法。

原始类型​

const userName: string = 'Tom';
const age: number = 24;
const enabled: boolean = true;
const undef: undefined = undefined;
const empty: null = null;
const largeNumber: bigint = 9007199254740991n;
const uniqueKey: symbol = Symbol('unique');

bigint 字面量要求编译目标至少为 ES2020。简单赋值通常可以省略类型注解,由编译器推断。

数组与元组​

数组中的元素类型通常相同;元组可以约束每个位置的类型和元素数量。

const numbers: number[] = [1, 2, 3];
const scores: Array<number> = [90, 95]; // 与 number[] 等价

const person: [string, number, boolean] = ['Tom', 24, true];
const optionalPerson: [name: string, age?: number] = ['Tom'];
const namedPerson: [name: string, age: number, enabled?: boolean] = ['Tom', 24];

const coordinates: readonly [number, number] = [10, 20];
const readonlyNumbers: readonly number[] = [1, 2, 3];

元组标签用于说明各位置的含义,不会生成对象属性;readonly 在类型检查时禁止修改元素。

对象类型​

用接口或类型别名描述对象的属性,? 表示可选属性,readonly 表示只读属性。

interface User {
readonly id: number;
name: string;
age?: number;
}

const user: User = { id: 1, name: 'Tom' };
user.name = 'Alice';

object 只约束值为非原始值,不描述业务属性。具体区别见 object、Object 与空对象类型。

集合类型​

const numberSet: Set<number> = new Set([1, 2, 3]);
const objectSet: WeakSet<object> = new WeakSet([{ count: 100 }]);

const schoolMap: Map<string, number> = new Map([
['school', 1],
['school2', 2],
]);

const metadata: WeakMap<object, string> = new WeakMap();
const key = { id: 1 };
metadata.set(key, 'cached');

Set<T> 约束集合元素,Map<K, V> 分别约束键和值。这里用对象作为弱集合元素和弱映射的键;弱引用不会阻止这些对象被垃圾回收。

联合类型与特殊类型​

type Status = 'loading' | 'success' | 'error';
const status: Status = 'loading';

let result: string | number = 1;
result = 'done';

const input: unknown = 'hello';
if (typeof input === 'string') {
console.log(input.toUpperCase());
}

function log(message: string): void {
console.log(message);
}

function fail(message: string): never {
throw new Error(message);
}
  • any:放弃相关类型检查,使用时需控制范围。
  • unknown:可以接收任意值,具体操作前需要检查并缩小类型。
  • void:通常用于不需要使用返回值的函数。
  • never:表示不可能出现的值,也用于表示函数不会正常返回。