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

Hon*_*iao 70 typescript

我有一个变量.

abc:number|string;
Run Code Online (Sandbox Code Playgroud)

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

if (abc.type === "number") {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

bas*_*rat 109

用于:

abc:number|string;
Run Code Online (Sandbox Code Playgroud)

使用JavaScript运算符typeof:

if (typeof abc === "number") {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

TypeScript理解 typeof

这被称为打字机.

更多

对于您将使用的课程,instanceof例如

class Foo {}
class Bar {} 

// Later
if (fooOrBar instanceof Foo){
  // TypeScript now knows that `fooOrBar` is `Foo`
}
Run Code Online (Sandbox Code Playgroud)

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

  • 添加了关于“ instanceof”的注释,即使这不是问的问题。 (2认同)
  • 没有回答问题。这不会获取它确认它是或不是您提供的类型的类型。 (2认同)

Lau*_*ens 38

我想补充一点,如果要比较对象使用instanceof,TypeGuard只能处理字符串或数字

if(task.id instanceof UUID) {
  //foo
}
Run Code Online (Sandbox Code Playgroud)

  • 真的。值得注意的是,您可以使用“类”来执行此操作,但不能使用 TypeScript“接口”或“类型”来执行此操作,因为它们不存在于导出的 JavaScript 文件中。 (7认同)

art*_*ohe 24

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

相反,您可以使用typecast + function 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是在 ES2017 中编译的 JavaScript:

function start(vehicle) {
    vehicle.drive();
    if (vehicle.ringTheBell) {
        const bike = vehicle;
        bike.ringTheBell();
    }
    else {
        const car = vehicle;
        car.honkTheHorn();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是接口与类的一个非常重要的区别!我希望有一种更惯用的方法来做到这一点,但这个建议效果很好。 (3认同)

Max*_*man 15

我怀疑您可以稍微调整一下您的方法并使用与此处示例类似的内容:

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}
Run Code Online (Sandbox Code Playgroud)

  • https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-in-operator-narrowing (2认同)

Wil*_*een 10

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')
}
Run Code Online (Sandbox Code Playgroud)

除了typeof运算符之外,还有内置的类型保护器,例如instanceofin甚至是您自己的类型保护器。


Abh*_*ash 6

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

console.log(isBoolean(this.myVariable));
Run Code Online (Sandbox Code Playgroud)

同样,我们有

isNumber(this.myVariable);
isString(this.myvariable);
Run Code Online (Sandbox Code Playgroud)

等等。

  • 您需要导入 `util` 才能访问这些函数(例如,`import { isString } from 'util';` (4认同)
  • 现在已弃用,请使用 if (typeof value === 'string') 代替 (3认同)