Typescript类型保护:使用in运算符

Raf*_*ero 1 typescript

我正在学习TypeScript,并通过官方DOCS进行有关Type Guard的练习。

我正在使用TypeScript 3.5.3测试提供的示例(或多或少):

function exec(strOrNum: string | number) {
    if ("substring" in strOrNum) {
        return strOrNum.substring(1);
    }
    return strOrNum.toExponential(2);
}
Run Code Online (Sandbox Code Playgroud)

But VSCode is trowing the following error:

The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)

I don't understand it, any idea?

DaG*_*ner 5

The in operator returns true if the specified property is in the specified object or its prototype chain.

This means it operates on objects (or arrays) and not strings.

If you want to add a type guard to differentiate between string and number you have to use typeof:

function exec(strOrNum: string | number) {
    if (typeof strOrNum === "string") {
        return strOrNum.substring(1);
    }
    return strOrNum.toExponential(2);
}
Run Code Online (Sandbox Code Playgroud)

You would use the in operator if you have a union of two interfaces:

interface A {
    a: string;
}

interface B {
    b: number;
}


function test(arg: A | B): string {
    if ('a' in arg) {
        return arg.a;
    }
    return arg.b.toFixed(2);
}

Run Code Online (Sandbox Code Playgroud)