【发布时间】:2018-05-30 12:40:06
【问题描述】:
typescript handbook on user defined type guards 将示例类型保护定义为
function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
箭头函数有对应的语法吗?
【问题讨论】:
标签: typescript types arrow-functions
typescript handbook on user defined type guards 将示例类型保护定义为
function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
箭头函数有对应的语法吗?
【问题讨论】:
标签: typescript types arrow-functions
是的,就像您返回 boolean 一样,您只需返回 pet is Fish:
const isFish: (pet: Fish | Bird) => pet is Fish = pet => (pet as Fish).swim !== undefined
箭头函数被声明为单一类型 ((pet: Fish | Bird) => pet is Fish),而不是单独声明参数和返回类型。
【讨论】:
使用类型断言而不是类型声明:
const isFish = (pet => !!pet.swim) as (pet) => pet is Fish
但是,鉴于它更冗长,我更愿意将类型保护编写为普通函数,除非您真的需要 this 绑定,但这可能是代码异味。
【讨论】:
作为替代方案,这也有效
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');
【讨论】:
TypeScript 支持箭头函数类型保护(2017 年可能不是这样)。以下现在按预期工作。我在生产代码中经常使用这种风格:
const isFish = (pet: Fish | Bird): pet is Fish =>
(pet as Fish).swim !== undefined;
【讨论】: