这是我的问题:
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
}
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
打字稿显示它foo的类型为T | CSSRule | Node。但是,forForEachList的类型只允许单个类型的列表,而不是联合。如果我删除 CSSRule、Attr 和 Node 的条件,它就可以正常工作。为什么这里foo不是类型T?
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |