我有一个变量。
abc:number|string;
我如何检查它的类型?我想做的事情如下:
if (abc.type === "number") {
// do something
}
我有一个变量。
abc:number|string;
我如何检查它的类型?我想做的事情如下:
if (abc.type === "number") {
// do something
}
当前回答
Type of可以用于此
if (typeof abc === "number") {
// number
} else if (typeof abc === "string"){
//string
}
其他回答
Type of可以用于此
if (typeof abc === "number") {
// number
} else if (typeof abc === "string"){
//string
}
因为Typescript 4.4你可以像下面这样做:
function foo(arg: unknown) {
const argIsString = typeof arg === "string";
if (argIsString) {
console.log(arg.toUpperCase());
}
}
我检查了一个变量,如果它是布尔或不是如下
console.log(isBoolean(this.myVariable));
类似地,我们有
isNumber(this.myVariable);
isString(this.myvariable);
等等。
我想补充的是,TypeGuards只适用于字符串或数字,如果你想比较一个对象使用instanceof
if(task.id instanceof UUID) {
//foo
}
我已经搜索了很多如何检查我的字符串变量是否等于我的类型,没有发现任何有意义的东西,因为任何类型的接口都不存在于运行时。 所以我们需要在运行时得到这个。 我想出了一个解决办法。
type MyType = 'one'|'two';
function isMyType(val: string): val is MyType {
const list:MyType[] = ['one','two'];
return list.includes(val as MyType);
}
...
const incomingValue = 'one';
if(isMyType(incomingValue)) {
// here typescript see incomingValue as MyType
}