在 TypeScript 中使用 is 运算符的原因是什么?

OPV*_*OPV 14 typescript typescript2.0

在这种情况下,在 TypeScript 中使用 is 运算符的原因是什么?

type Species = "cat" | "dog";


interface Pet {
   species: Species
}

interface Cat extends Pet {

}

function petIsCat(pet: Pet): pet is Cat {
   return pet.species === "cat";
}
Run Code Online (Sandbox Code Playgroud)

为什么要使用pet is Cat替代boolean,如果身体恢复bool类型?

小智 17

boolean 只是一种数据类型,而 'is' 运算符用于类型测试。让我稍微改变一下你的例子:

type Species = 'cat' | 'dog';

interface Pet {
    species: Species;
}

class Cat implements Pet {
    public species: Species = 'cat';
    public meow(): void {
        console.log('Meow');
    }
}

function petIsCat(pet: Pet): pet is Cat {
    return pet.species === 'cat';
}

function petIsCatBoolean(pet: Pet): boolean {
    return pet.species === 'cat';
}

const p: Pet = new Cat();

p.meow(); // ERROR: Property 'meow' does not exist on type 'Pet'.

if (petIsCat(p)) {
    p.meow(); // now compiler is know for sure that the variable is of type Cat and it has meow method
}

if (petIsCatBoolean(p)) {
    p.meow(); // ERROR: Property 'meow' does not exist on type 'Pet'.
}
Run Code Online (Sandbox Code Playgroud)

当然你可以使用类型转换:

(<Cat>p).meow(); // no error
(p as Cat).meow(); // no error
Run Code Online (Sandbox Code Playgroud)

但这取决于场景。