TypeScript:map()中的时髦类型推断

时间:2019-10-03 17:38:58

标签: typescript typescript-generics

我今天犯了一个错误:

  private maybeCreatePager(eventIssueName: Maybe<string>): Maybe<Pager<T>> {
    return eventIssueName.map(n => {
      this.issuePagers[n] = this.createPager(n);  // WRONG. n is of type string but createPager expects a Maybe<string>
      return this.issuePagers[n];
    })
  }

  private createPager(eventIssueName: Maybe<string>): Pager<T> {
    throw new Error('not implemented');
  }

但是,除非我明确给出n的类型,否则类型捕获器不会抱怨。应该不是很明显吗?

这是我的Maybe实现的一部分:

export abstract class Maybe<T> {

  static unit<U>(x: U) { return new Just<U>(x); }
  abstract bind<U>(f: (T) => Maybe<U>): Maybe<U>;

  map<U>(f: (T) => U): Maybe<U> {
    return this.bind(x => Maybe.unit(f(x)));
  }
}

为什么不推断n的类型?

0 个答案:

没有答案