我有一个变量。
abc:number|string;
我如何检查它的类型?我想做的事情如下:
if (abc.type === "number") {
// do something
}
我有一个变量。
abc:number|string;
我如何检查它的类型?我想做的事情如下:
if (abc.type === "number") {
// do something
}
当前回答
我想补充的是,TypeGuards只适用于字符串或数字,如果你想比较一个对象使用instanceof
if(task.id instanceof UUID) {
//foo
}
其他回答
因为Typescript 4.4你可以像下面这样做:
function foo(arg: unknown) {
const argIsString = typeof arg === "string";
if (argIsString) {
console.log(arg.toUpperCase());
}
}
其他答案是正确的,但当你处理接口时,你不能使用typeof或instanceof,因为接口不会被编译成javascript。
相反,你可以使用类型转换+函数check typeguard来检查你的变量:
interface Car {
drive(): void;
honkTheHorn(): void;
}
interface Bike {
drive(): void;
ringTheBell(): void;
}
function start(vehicle: Bike | Car ) {
vehicle.drive();
// typecast and check if the function exists
if ((<Bike>vehicle).ringTheBell) {
const bike = (<Bike>vehicle);
bike.ringTheBell();
} else {
const car = (<Car>vehicle);
car.honkTheHorn();
}
}
这是ES2017中编译后的JavaScript:
function start(vehicle) {
vehicle.drive();
if (vehicle.ringTheBell) {
const bike = vehicle;
bike.ringTheBell();
}
else {
const car = vehicle;
car.honkTheHorn();
}
}
我检查了一个变量,如果它是布尔或不是如下
console.log(isBoolean(this.myVariable));
类似地,我们有
isNumber(this.myVariable);
isString(this.myvariable);
等等。
我已经搜索了很多如何检查我的字符串变量是否等于我的类型,没有发现任何有意义的东西,因为任何类型的接口都不存在于运行时。 所以我们需要在运行时得到这个。 我想出了一个解决办法。
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
}
我想补充的是,TypeGuards只适用于字符串或数字,如果你想比较一个对象使用instanceof
if(task.id instanceof UUID) {
//foo
}