操作符
以下是 TypeScript 特有操作符的汇总,这些操作符主要用于类型系统、类型断言和类型安全增强:
一、类型断言操作符
1. 类型断言(Type Assertion)
强制将某个值视为特定类型,绕过类型检查。
// 方式1:as 语法
const value: unknown = "hello";
const strLength: number = (value as string).length;
// 方式2:尖括号语法(JSX中不支持)
const strLength2: number = (<string>value).length;
// 双重断言(谨慎使用)
const someValue: unknown = 123;
const strValue = someValue as unknown as string;
2. 非空断言操作符(!)
断言某个值不为 null 或 undefined,用于消除类型中的 null 和 undefined。
// 函数参数
function printName(name: string | null) {
console.log(name!.toUpperCase()); // 断言 name 不为 null
}
// DOM 元素
const element = document.getElementById("app")!; // 断言元素存在
二、空值处理操作符
1. 可选链操作符(?.)
安全访问可能为 null 或 undefined 的属性,避免运行时错误。
const user = {
address: {
street: "123 Main St"
}
};
const street = user.address?.street; // 安全访问,若 address 不存在返回 undefined
const length = user.address?.street?.length; // 多级可选链
2. 空值合并操作符(??)
仅当左侧值为 null 或 undefined 时,才返回右侧的默认值。
const value = null ?? "default"; // "default"
const value2 = 0 ?? 100; // 0 (仅 null/undefined 触发)
const value3 = "" ?? "empty"; // "" (空字符串不触发)
三、类型守卫操作符
用于在运行时检查类型,缩小类型范围。
1. typeof
检查基本类型(string, number, boolean, object, function 等)。
function printValue(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase()); // 类型缩小为 string
} else {
console.log(value.toFixed(2)); // 类型缩小为 number
}
}
2. instanceof
检查对象是否是某个类的实例。
class Dog { bark() {} }
class Cat { meow() {} }
function speak(animal: Dog | Cat) {
if (animal instanceof Dog) {
animal.bark(); // 类型缩小为 Dog
} else {
animal.meow(); // 类型缩小为 Cat
}
}
3. in
检查对象是否具有某个属性。
function printId(entity: { id: number } | { name: string }) {
if ("id" in entity) {
console.log(entity.id); // 类型缩小为 { id: number }
} else {
console.log(entity.name); // 类型缩小为 { name: string }
}
}
四、类型操作符
1. keyof
获取类型的所有公共属性名组成的联合类型。
type Person = {
name: string;
age: number;
};
type PersonKeys = keyof Person; // "name" | "age"
2. typeof
获取值的类型(与 JavaScript 的 typeof 操作符不同)。
const person = { name: "Alice", age: 30 };
type PersonType = typeof person; // { name: string; age: number }
3. 索引访问操作符([])
通过类型的属性名获取属性类型。
type Person = {
name: string;
age: number;
address: { street: string };
};
type AgeType = Person["age"]; // number
type StreetType = Person["address"]["street"]; // string
4. 条件类型(T extends U ? X : Y)
根据条件选择类型。
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
5. 映射类型
基于现有类型创建新类型。
// 只读版本
type ReadonlyPerson = Readonly<Person>;
// 可选版本
type PartialPerson = Partial<Person>;
// 自定义映射
type Keys = "name" | "age";
type PersonSubset = { [K in Keys]: string }; // { name: string; age: string }
6. 泛型约束(extends)
限制泛型类型的范围。
function getLength<T extends { length: number }>(arg: T) {
return arg.length;
}
五、其他操作符
1. 交叉类型(&)
组合多个类型为一个类型,包含所有类型的属性。
type Admin = { role: string };
type User = { name: string };
type AdminUser = Admin & User; // { role: string; name: string }
2. 联合类型(|)
允许变量具有多种类型之一。
let value: string | number;
value = "hello"; // 合法
value = 100; // 合法
// value = true; // 错误:不是 string 或 number
3. 类型别名(type)
为类型创建自定义名称。
type Point = {
x: number;
y: number;
};
type ID = string | number;
总结
TypeScript 的特有操作符主要服务于类型系统,通过类型断言、类型守卫和类型操作,增强代码的类型安全性和表达力。合理使用这些操作符可以让你的代码在编译阶段发现更多错误,减少运行时异常。