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

问题描述 投票:0回答:2

在这种情况下,在 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";
}

如果 body 返回 bool 类型,为什么要使用

pet is Cat
代替
boolean

typescript typescript2.0
2个回答
47
投票

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 knows 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'.
}

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

(<Cat>p).meow(); // no error
(p as Cat).meow(); // no error

但这取决于场景。


文档:


1
投票

我的理解是这样的:

宠物是猫

  • 是函数返回类型。
  • 因为它具有“变量是类型”语法,所以称为用户定义类型检查
  • 此函数返回类型可以在编译时由代码“类型检查器”使用: 所以: 在你的代码编辑器中,如果你的代码编辑器配备了一些 TS 的类型检查软件,它会显示 0 个编译错误,并且在用户定义类型保护之后会知道 person1 的类型:
const isPerson = (object: any): object is Person => "address" in object

interface Person {
    address: string
}
// type of person1 is {address: string}
const person1 = {
    address: "rue"
}

if(isPerson(person1)){
    console.log(person1.address) // type is Person as opposed to {address: string}
} else {
    console.log("person is not a Person")
}

希望有帮助

© www.soinside.com 2019 - 2024. All rights reserved.