【问题标题】:Exporting utility functions in typescript?在打字稿中导出实用功能?
【发布时间】:2018-06-24 03:02:11
【问题描述】:

我正在尝试这样做(伪代码):

export const isDefined:Function<boolean> = ((value:any)) => {
    return !(value==null);
};

isDefined 函数在 value 参数不为 null 或未定义时返回布尔值,并将 any 类型作为参数。关于如何让它工作的想法?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    建议:尽可能避免使用Function。它消除了类型安全:

    // these should error, but they don't
    isDefined()
    isDefined(1, 2, 3, 'too', 'many', 'args')
    

    要保存类型签名,请去掉Function。为简单起见,也可以使用!=

    export const isDefined = (value: any): boolean => {
      return value != null
    }
    

    作为奖励,您可以滥用泛型使函数更智能。在这里,该函数使用 generic T 来推断传递给它的内容的类型,然后它使用 type guard 在某些情况下缩小类型,例如if 语句。 (注意:我将其定义为 function 以使其在 .tsx 文件中工作。由于 JSX 的歧义,无法解析单泛型箭头函数。)

    export function isDefined<T>(value: T | null | undefined): value is T {
      return value != null
    }
    
    declare const message: string | undefined
    if (isDefined(message)) {
      message // here, message is string
    } else {
      message // here, message is undefined
    }
    

    【讨论】:

    • 非常酷!您能否详细说明value is T 部分的作用?
    • 这是类型保护部分。我链接了一些文档以获取更多信息。如果你用string | undefined 调用isDefinedT 变成string。使用此功能,TS 将根据函数的返回类型“智能转换”变量的类型。
    • 非常感谢-您知道是否仍然可以指示函数返回类型吗?只是好奇...
    • 嗯,已经说明了。 value is T 只是boolean 的智能版本¯\_(ツ)_/¯
    • null !== undefined。我不会在名为isDefined 的函数中检查null。否则,非常酷!
    【解决方案2】:

    好的 - 我终于明白了:

    export const isDefined: Function = (value: any): boolean => {
      return !(value == null);
    };
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2016-02-10
      • 2013-03-17
      • 2017-02-03
      • 2022-01-24
      • 2021-11-17
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多