为什么打字稿无法正确推断条件的泛型?

时间:2020-06-29 10:27:06

标签: typescript

这是我的问题:

export type ForEachList<T> =
    T extends Element ? (NodeListOf<T> | HTMLCollectionOf<T>) :
    T extends CSSRule ? CSSRuleList :
    T extends Attr ? NamedNodeMap :
    T extends Node ? (Node[] | NodeList) :
    T[];

export function forEach<T>(array: ForEachList<T>,
                        forEachFn: (value: T, index: number, arr: ForEachList<T>, done: () => void) => boolean | void,
                        thisArg?: any): void { 
    for (let i = 0; i < array.length; i++) {
        const foo = array[i];
        forEachFn.call(thisArg, foo, i, array, () => { /* empty on purpose */ });
//                              ^^^ error here
    }
}
Argument of type 'Node | CSSRule | T' is not assignable to parameter of type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'Node | CSSRule | T'.
    Type 'Node' is not assignable to type 'T'.
      'T' could be instantiated with an arbitrary type which could be unrelated to 'Node'.(2345

Playground Link

打字稿显示foo的类型为T | CSSRule | Node。但是,ForEachList的类型只允许列出单个类型,而不是联合。如果删除CSSRule,Attr和Node的条件,它将正常工作。为什么这里的foo不是T类型?

0 个答案:

没有答案