TypeScript Version: 2.7.0
Search Terms:
typeof + transitive + type guard + typeof same
Code
function test(a: string | number, b: string | number) {
if (typeof a === typeof b && typeof a === 'string') return b.length
}
Expected behavior:
variable b be asserted as string type.
Actual behavior:
TS report: Property 'length' does not exist on type 'string | number'. at b.length
Playground Link:
Playground
Related Issues:
This could prove very useful.
Another real life example:
type FormStep = 'step1' | 'step2' | 'step3' ...
function view(step: FormStep, data: ...) {
if (step === 'step1' && canAccessStep1(data.step1relatedStuff))
return step1View(data.step1relatedStuff)
if (step === 'step2' && canAccessStep2(data.step2relatedStuff))
return step2View(data.step2relatedStuff)
// The compiler can't infer that one anymore, because of the &&s above
else
return defaultView()
}
It seems like the same kind of limitations in control flow analysis; I can create a new ticket if it's not.
Any plan on this feature?
Most helpful comment
This could prove very useful.
Another real life example:
It seems like the same kind of limitations in control flow analysis; I can create a new ticket if it's not.