I have this code:
const list = ['a', 'b', '= c', 'd']
if (list.some(element => element.includes('='))) {
const elementWithEqualSign = list.find(element => element.includes('='))
}
In here elementWithEqualSign has type string | undefined, while in fact it should be only string, due to the condition above filtering the possibility of undefined. Is there a way to tell it to automatically narrow the type without using type assertion as string? I suppose the answer is somewhere in TypeScript: Documentation - Narrowing, but I don't know to find it out.
In the general case, no.
Consider the situation where you use a different condition in the
.some()from the one in.find().How would the compiler figure out (automatically) that the first condition does/does not change the return type of
.find().What if the condition is arbitrarily complicated? What if, for example, it checked each element against a REST API? Even with an apparently identical condition, it could return a different result the second time (this is sometimes referred to as time-of-check-time-of-use -- TOCTOU), meaning that
undefinedis a possible type.Use a type assertion.