type refinements
从函数。
如何创建
type guard
TypeScript示例:
function isString(arg: Showable): arg is string {
return typeof arg === 'string';
}
流量
/* @flow */
type Showable = number | string;
// ok
function barOk (arg: Showable) {
return typeof arg === 'string' ? arg.length : (arg + 1);
}
// type guard function
function isString(arg: Showable) {
return typeof arg === 'string';
}
// Error
function barError (arg: Showable) {
return isString(arg) ? arg.length : (arg + 1);
// ^ Cannot get `arg.length` because property `length` is missing in `Number`
}