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