2. 在项目中如何用 TS 解决类型边界问题? 类型保护
约 330 字大约 1 分钟
2025-06-08
这个问题主要考察的是类型缩小、类型保护。
typeof
和 instanceof
的区别
typeof
:适用于判断八大基本类型,如string
、number
、boolean
、undefined
、symbol
、bigint
、function
、object
。instanceof
:主要是通过构造函数的指向来判断某个对象是否属于某个特定的构造函数或者类的实例。
if
和 switch
的区别
if
:适用于判断条件,根据条件的真假来决定是否执行特定的代码块。switch
:适用于根据不同的条件值执行不同的代码块。
in
运算符
用于判断对象自身或其原型链中是否存在给定的属性,若存在则返回 true,否则返回 false。
prop in target
左操作数为待测试的属性名,右操作数为测试对象。
实例
// if 语句
function f(x: Date | RegExp): void {
if (x instanceof Date) {
console.log("type is Date");
}
if (x instanceof RegExp) {
console.log("type is RegExp");
}
}
// switch 语句
function getScore(value: number | string): number {
switch (typeof value) {
case "number":
// %inferred-type: number
value;
return value;
case "string":
// %inferred-type: string
value;
return value.length;
default:
throw new Error("Unsupported value: " + value);
}
}
// in 运算符
interface A {
x: number;
}
interface B {
y: string;
}
function f(x: A | B): void {
if ("x" in x) {
console.log("type is B");
} else {
console.log("type is A");
}
}
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于