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

Arrow style user defined type guard?

typescript handbook on user defined type guards 定义了一个示例类型保护作为

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

箭头函数有对应的语法吗?

是的,就像您 returned boolean 一样,您只需 return pet is Fish:

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

箭头函数被声明为单一类型 ((pet: Fish | Bird) => pet is Fish),而不是参数和 return 类型分开声明。

使用类型断言而不是类型声明:

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;