箭头样式用户定义的类型保护?

时间:2017-12-16 15:06:40

标签: typescript types arrow-functions

typescript handbook on user defined type guards将示例类型保护定义为

function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}

箭头功能是否有相应的语法?

4 个答案:

答案 0 :(得分:2)

使用类型转换而不是类型声明:

const isFish = (pet => !!pet.swim) as (pet) => pet is Fish 

然而,鉴于它更冗长,我宁愿将类型保护写为普通函数,除非你真的需要this绑定,但这可能是代码味道。

答案 1 :(得分:1)

是的,就像您返回boolean一样,只需返回pet is Fish

const isFish: (pet: Fish | Bird) => pet is Fish = pet => (pet as Fish).swim !== undefined

箭头函数被声明为单个类型((pet: Fish | Bird) => pet is Fish)而不是参数和返回类型。

答案 2 :(得分:1)

TypeScript支持箭头功能类型防护(2017年可能不是这种情况)。现在,以下各项将按预期工作。我在生产代码中经常使用这种样式:

const isFish = (pet: Fish | Bird): pet is Fish => 
  (pet as Fish).swim !== undefined;

答案 3 :(得分:0)

作为替代方案,这也有效

const isFish = (pet: any): pet is Fish => !!pet.swim;

或者如果您希望更明确

const isFish = (pet: any): pet is Fish => pet.swim === 'function';

同时可以对属性进行测试

const isFish = (pet: any): pet is Fish => pet.hasOwnProperty('genus');