ts中的类型判断
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
在TypeScript中,你可以使用多种方式来判断一个变量的类型。以下是一些常用的方法:
typeof
用于检查基础类型(string
,number
,boolean
,symbol
,undefined
,bigint
)。
const str = "Hello, World!";
if (typeof str === "string") {
// str是字符串类型
}
instanceof
用于判断对象的类型。
class MyClass {}
const myObject = new MyClass();
if (myObject instanceof MyClass) {
// myObject是MyClass的实例
}
in
操作符用于检查对象是否具有某个属性。
interface MyInterface {
prop: string;
}
const myObj: MyInterface = { prop: "value" };
if ("prop" in myObj) {
// myObj有一个名为'prop'的属性
}
- 使用自定义类型守卫函数。
function isMyType(arg: any): arg is MyType {
return typeof arg.myProperty === "string";
}
const myVar = { myProperty: "value" };
if (isMyType(myVar)) {
// myVar是MyType类型
}
- 使用
typeof
结合类型别名进行判断。
type MyType = {
prop: string;
};
const myVar: MyType = { prop: "value" };
if (typeof myVar.prop === "string") {
// myVar.prop是字符串类型
}
- 使用
type of
结合内置类型守卫进行判断。
type MyType = string | number;
const myVar: MyType = "value";
if (typeof myVar === "string") {
// myVar是字符串类型
}
以上方法可以根据需要选择适合的方式来判断类型。
评论已关闭