Why isn't the type argument inferred as a union type?

后端 未结 1 1720
傲寒
傲寒 2020-12-21 06:35

This code

declare function fn(array: T[], predicates: ((arg: T) => U)[]): [T, U];
let a = fn([1, 2, 3], [x => 2, x => \'s\']);


        
相关标签:
1条回答
  • 2020-12-21 07:11

    TypeScript in general will not synthesize a union type during generic inference. The reason, in simplified terms, is that it's not desirable to do inference like this:

    function compare<T>(x: T, y: T): number { ... }
    // Could infer T: string | number here... but that'd be bad
    compare('oops', 42);
    

    If a generic type can't be formed by picking one of the inference candidates, you'll get the error you posted.

    Experience informed this choice. In prior versions (before union types existed), {} would be inferred if no inference candidate was a supertype of all candidates. In practice this led to a lot of missed errors that looked like the example above.

    0 讨论(0)
提交回复
热议问题