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

时间:2018-07-01 15:56:28

标签: typescript typescript2.0

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

Address 4210695 contains Arijit
Address 4210701 contains Rohit
Address 4210711 contains Debojyoti
Address 45 contains Abhisek

如果正文返回布尔类型,为什么要使用type Species = "cat" | "dog"; interface Pet { species: Species } interface Cat extends Pet { } function petIsCat(pet: Pet): pet is Cat { return pet.species === "cat"; } 而不是pet is Cat

1 个答案:

答案 0 :(得分:2)

布尔值只是一种数据类型,而'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'.
}

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

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

但这取决于情况。