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

如何在Typescript中获取变量类型?,typescript,Typescript,我有一个变量 abc:number|string; 如何检查其类型?我想做如下事情: if (abc.type === "number") { // do something } 用于: 使用JavaScript运算符typeof: if (typeof abc === "number") { // do something } TypeScript理解typeof我想补充一点,typeguard只对字符串或数字起作用,如果您想比较对象,请使用instanceof if(t

我有一个变量

abc:number|string;
如何检查其类型?我想做如下事情:

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

使用JavaScript运算符
typeof

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

TypeScript理解
typeof
我想补充一点,typeguard只对字符串或数字起作用,如果您想比较对象,请使用instanceof

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

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

console.log(isBoolean(this.myVariable));
同样地,我们也有

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

以此类推。

其他答案是正确的,但是当你处理接口时,你不能使用typeof或instanceof,因为接口没有编译成javascript

您可以使用typecast+函数检查来检查变量:

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();
    }
}
在typescript中键入卫士 要确定条件语句后的变量类型,可以使用类型保护。typescript中的类型保护如下所示:

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

换句话说,它是一个条件块中的表达式,typescript编译器从中获得足够的信息来缩小类型。该类型在类型保护的块中更为具体,因为编译器已推断出有关该类型的更多信息

例子
除了
typeof
操作符之外,还有内置的类型保护,比如
instanceof
in
,甚至还有您自己的类型保护。

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


instanceof
上添加了注释,尽管这不是我要问的问题。对我来说很有用,但只是为了了解类型!!,自定义类型必须使用
instanceof
您需要导入
util
才能访问这些函数(例如,
import{isString}from'util';
debricated now,使用if(typeof value=='string'))相反,值得注意的是,您可以使用
class
es来实现这一点,但不能使用TypeScript
interface
s或
type
s,因为它们不存在于导出的JavaScript文件中。这是接口与类之间的一个非常重要的区别!我希望有一种更惯用的方式来实现这一点,但这个建议效果很好.
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();
    }
}
function start(vehicle) {
    vehicle.drive();
    if (vehicle.ringTheBell) {
        const bike = vehicle;
        bike.ringTheBell();
    }
    else {
        const car = vehicle;
        car.honkTheHorn();
    }
}
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')
}
function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}