【问题标题】:Flowtype: How to create type guard function?Flowtype:如何创建类型保护功能?
【发布时间】:2018-10-10 23:42:20
【问题描述】:

我想从函数中使用type refinements。 如何在流中创建type guard 函数(TypeScript)?

TypeScript 示例:

function isString(arg: Showable): arg is string {
    return typeof arg === 'string';
}

II

/* @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`
}

【问题讨论】:

    标签: flowtype


    【解决方案1】:

    将您的 isString 函数更改为以下内容:

    function isString(arg: Showable): boolean %checks {
        return typeof arg === 'string';
    }
    

    Predicate Functions

    【讨论】:

    • 打字稿版本:function isString(arg: Showable): arg is boolean {...}
    猜你喜欢
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2019-12-27
    • 2011-06-26
    • 2022-01-12
    • 2019-03-01
    相关资源
    最近更新 更多