이 코드는 typescript 2.3에서는 제대로 작동하지만 typescript 2.4에서는 실패합니다. 이유를 설명해 주시겠습니까?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;
}
오류 메시지 : 귀하의 예제를 작동하게하기 위해
error TS2322: Build:Type 'Node' is not assignable to type 'Element'.
'HTMLFontElement'에서'Node'로'find'의 유추 된 리턴 타입을 변경 한 커밋은 다음과 같습니다 : [일반 문맥 서명을 사용하는 람다에 대한 일반적인 유형을 추론합니다] (https://github.com/Microsoft/TypeScript/commit/872e916019a1a6cd33e03c1837569d4845c54576) (2.4.1에서 릴리스 됨). 유형 가드의 추측에 대한 영향이 의도적인지 아닌지는 잘 모르겠다. 문제를 게시하는 것이 좋습니다. – artem
이 문제는 알려진 문제이며 [2.7 (https://github.com/Microsoft/TypeScript/pull/17600)에서 수정 될 가능성이 있음)입니다. 그 동안이 코드를 컴파일하려면 Fenton의 답변에서 제안한 바와 같이 명시 적 형식 매개 변수를 추가해야합니다.'nodes.find ((n) : n은 HTMLFontElement => ...)' –
artem