【问题标题】:TypeScript error. Fixed but can't explain it打字稿错误。已修复但无法解释
【发布时间】:2017-04-27 09:40:15
【问题描述】:

破解密码:

ngOnInit(){
    Observable.fromEvent(this.el.nativeElement, 'keyup')
    .map((e:any) => {e.target.value})
    .filter((text:string) => text.length < 3)
    .debounceTime(250)
    .do(() => this.loading.next(true))
    //search youtube
    .map((query: string)=> {this.youtube.search(query)})
}

错误:

[ts] 无法从用法中推断类型参数“T”的类型参数。考虑明确指定类型参数。 类型参数候选“void”不是有效的类型参数,因为它不是候选“字符串”的超类型。 任何

修复:

如果我从 e.target.value(第 3 行)中删除大括号,一切正常。为什么会这样?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    这里有 C# 背景,但我认为同样的逻辑也适用于 TypeScript。

    花括号允许您在 lambda 中输入多行代码,例如

    .map((e:any) => {
        console.log('Hello');
        return e.target.value;
    })
    

    也就是说在使用花括号的时候需要使用return e.target.value;,这样代码块才会返回一个值来满足map函数的要求。

    不使用花括号会导致 e.target.value 从对 map 的调用中隐式返回,因此无需包含 return

    【讨论】:

      【解决方案2】:

      它们对应ES6 arrow function的2个语法,即:

      (param1, param2, …, paramN) => { statements }
      (param1, param2, …, paramN) => expression
      

      这使得 tsc 推断的返回类型不同:

      .map((e:any) => {e.target.value})
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~
           an arrow function that have no return, and effectively returns undefined.
           TypeScript compiler infers such function to have return type "void".
      
      .map((e:any) => e.target.value)
           ~~~~~~~~~~~~~~~~~~~~~~~~~
           an arrow function that returns e.target.value
           the compiler inters the return type to be "any"
      

      【讨论】:

      • 很有意义。谢谢。
      猜你喜欢
      • 2022-12-16
      • 2019-02-07
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 2020-09-20
      • 2022-11-10
      • 1970-01-01
      • 2019-04-16
      相关资源
      最近更新 更多