【问题标题】:How to define result type of anonymous function?如何定义匿名函数的结果类型?
【发布时间】:2022-08-05 22:25:28
【问题描述】:

我想在array.map(..) 中使用元组作为结果类型,并且我正在寻找一种不预先定义它们的类型的方法,因为我的函数通常很短并且导致元组只有两个组件。

定义匿名函数的结果类型的正确语法是什么?

    标签: typescript functional-programming mapping


    【解决方案1】:
    
    // input
    let list: string[] = [ "a", "abc" ]
    
    // possible type definition
    type Tuple = [string, number];
    
    // verbose function definition
    function hello(s: string): Tuple
    {
        return [s, s.length];
    }
    
    
    // different ways to use .map() with 
    // same results to show syntax options
    
    let v0 = list.map( s => hello( s ) );
    
    let v1 = list.map( (s: string): Tuple => hello(s) );
    
    let v2 = list.map( (s: string): Tuple => {
      return [s, s.length]
     });
    
    let v3 = list.map( (s: string): [string, number] => {
      return [s, s.length]
     });
    
    let v4 = list.map( (s): [string, number] => {
      return [s, s.length]
     });
    
    let v5 = list.map( (s): [string, number] => [s, s.length] );
    
    
    

    在线尝试,立即错误突出显示www.typescriptlang.org

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      相关资源
      最近更新 更多