我有一个变量。

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;
}

其他回答

我检查了一个变量,如果它是布尔或不是如下

console.log(isBoolean(this.myVariable));

类似地,我们有

isNumber(this.myVariable);
isString(this.myvariable);

等等。

我怀疑你可以稍微调整一下你的方法,使用下面这个例子中的一些东西:

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;
}

我想补充的是,TypeGuards只适用于字符串或数字,如果你想比较一个对象使用instanceof

if(task.id instanceof UUID) {
  //foo
}

其他答案是正确的,但当你处理接口时,你不能使用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();
    }
}

Type of可以用于此

if (typeof abc === "number") {
    // number
} else if (typeof abc === "string"){
//string
}