我有一个变量。
abc:number|string;
我如何检查它的类型?我想做的事情如下:
if (abc.type === "number") {
// do something
}
我有一个变量。
abc:number|string;
我如何检查它的类型?我想做的事情如下:
if (abc.type === "number") {
// do something
}
当前回答
我怀疑你可以稍微调整一下你的方法,使用下面这个例子中的一些东西:
https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
其他回答
Type of可以用于此
if (typeof abc === "number") {
// number
} else if (typeof abc === "string"){
//string
}
我怀疑你可以稍微调整一下你的方法,使用下面这个例子中的一些东西:
https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
因为Typescript 4.4你可以像下面这样做:
function foo(arg: unknown) {
const argIsString = typeof arg === "string";
if (argIsString) {
console.log(arg.toUpperCase());
}
}
在typescript中输入保护
要在条件语句之后确定变量的类型,可以使用类型保护。typescript中的类型保护如下所示:
一个允许你缩小某物类型的表达式 在一个条件块中。
换句话说,它是一个条件块中的表达式,typescript编译器从中有足够的信息来缩小类型。在类型保护的块内,类型将更加特定,因为编译器已经推断出关于类型的更多信息。
例子
declare let abc: number | string;
// typeof abc === 'string' is a type guard
if (typeof abc === 'string') {
// abc: string
console.log('abc is a string here')
} else {
// abc: number, only option because the previous type guard removed the option of string
console.log('abc is a number here')
}
除了typeof操作符,还有内置的类型保护,比如instanceof, in,甚至你自己的类型保护。
我想补充的是,TypeGuards只适用于字符串或数字,如果你想比较一个对象使用instanceof
if(task.id instanceof UUID) {
//foo
}