如何在Typescript中获取变量类型?

时间:2016-02-22 05:33:43

标签: typescript

我有一个变量。

abc:number|string;

如何检查其类型?我想做类似下面的事情:

if (abc.type === "number") {
    // do something
}

7 个答案:

答案 0 :(得分:65)

对于:

abc:number|string;

使用 JavaScript 运算符typeof

if (typeof abc === "number") {
    // do something
}

TypeScript了解typeof

这被称为打字机。

更多

对于课程,您可以使用instanceof,例如

class Foo {}
class Bar {} 

// Later
if (fooOrBar instanceof Foo){
  // TypeScript now knows that `fooOrBar` is `Foo`
}

还有其他类型的警卫,例如inhttps://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html

答案 1 :(得分:36)

我想补充一点,如果要比较对象使用实例

,TypeGuards只适用于字符串或数字
if(task.id instanceof UUID) {
  //foo
}

答案 2 :(得分:8)

其他答案是正确的,但是在处理接口时,您不能使用typeof或instanceof,因为接口不会被编译为javascript。

相反,您可以使用 typecast +函数检查 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();
    }
}

答案 3 :(得分:4)

我已经检查了变量是否为布尔值,如下所示

sebuaharray arraynya = new sebuaharray();
arraynya.setIsiarray(arraysementara);}

类似地,我们有

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

以此类推。

答案 4 :(得分:1)

我怀疑您可以稍微调整一下方法,并按照此处的示例使用一些东西:

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

答案 5 :(得分:0)

打字稿中的类型防护

要在条件语句后确定变量的类型,可以使用类型保护。打字稿中的类型防护如下:

允许您缩小事物类型的表达式 在条件块内。

换句话说,它是一个条件块中的表达式,打字稿编译器从那里可以得到足够的信息来缩小类型。该类型将在类型防护的块内更具体,因为编译器已推断出有关该类型的更多信息。

示例

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运算符外,还内置了instanceofin之类的类型防护,甚至是您自己的类型防护。

答案 6 :(得分:0)

从 Typescript 4.4 开始,你可以像下面这样:

function foo(arg: unknown) {
    const argIsString = typeof arg === "string";
    if (argIsString) {
        console.log(arg.toUpperCase());
    }
}