다음 예에서 변수가 왜 누군가가 설명 할 수 z
유형이 number
있지만, 호출 내에서 f1(x.y)
, x.y
유형이number | undefined
const f1 = (value: number) => !!value;
const f2 = (x: { y: number | undefined}): void => {
if (x.y === undefined || !isFinite(x.y)) {
throw new Error('Not a number');
}
const z = x.y; // z & x.y has type number
['stuff', 'here'].find(item => f1(x.y)); // x.y has type number | undefined
};
저는이 질문이 정말 마음에 들었고 조사를했고 뭔가를 배웠습니다. OP가 언급했듯이 클로저, 특히 콜백과 관련이 있습니다. 그들이 오는 것을 설명하려고 노력하는 아래 코드에서 내 의견을 읽으십시오.
const f1 = (value: number) => !!value;
const f2 = (x: { y: number | undefined}): void => {
if (x.y === undefined || !isFinite(x.y)) {
throw new Error('Not a number');
}
// Here, you have ensured here that type of z is not changing
const z = x.y;
// `x.y` is mutable,
// As jcalz correctly mentioned in the comment,
// the compiler does not know that the `find` function executes the
// callback synchronously and immediately, and it is expensive
// to check if anyone has altered its type elsewhere before the
// callback was executed. So, it can't
// guarantee that the type of `x.y` stays number
// hence, Typescript expands `x.y` back to `number | undefined`
['stuff', 'here'].find(item => f1(x.y));
// This however knows type isn't changing
['stuff', 'here'].find(item => f1(z));
// However, this works because Typescript optimistically thinks
// the function, in our case `find`, does not have a side effect
// (referring the article noted below)
f1(x.y);
// In a parallel universe, where `find` is
// asynchronous like `timeout`,
// and executes the callback sometime later
// and we had the following line here
x.y = undefined
// Since the `find` function, in our parallel universe,
// would call the callback
// after we have assigned `x.y` as `undefined`
// it makes sense to expand the type in the callback within the find
// function back to number | undefined
};
여기에 흥미로운 기사가 있습니다. 정말 좋은 읽기 : https://herringtondarkholme.github.io/2017/02/04/flow-sensitive/
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다