此代码适用于typescript 2.3,但使用typescript 2.4失败。你能解释一下原因吗?
testFindTypeGuard.ts:
let el: Element;
const nodes: Node[] = [];
const result = nodes.find((n): n is HTMLFontElement => n.nodeName === "FONT");
el = result;
my.d.ts:
interface Array<T> {
find<U extends T>(predicate: (value: T, index: number, obj: Array<T>) => value is U): U | undefined;
}
错误消息:
错误TS2322:构建:类型&#39;节点&#39;不能分配给&#39;元素&#39;。
答案 0 :(得分:0)
为了使您的示例按预期工作,您需要向编译器描述U
。它并没有在概念上实现自动扩大型号防护装置的适用性。
当您使用类型保护作为if语句的一部分时,它将为您更改类型(在if和else中)。但是在您的示例中,您需要传递类型参数以到达您想要的位置:
const result = nodes.find<HTMLFontElement>((n): n is HTMLFontElement => n.nodeName === "FONT");
编译器 足够聪明,可以确定什么时候没有堆叠,以下内容会给你一个错误:
const result = nodes.find<HTMLDivElement>((n): n is HTMLFontElement => n.nodeName === "FONT");
如果您认为编译器在以前的版本上做得更好,您可能想在GitHub上引发一个问题......尽管您may have done so already。