Typescript: Make the type guarding on 'typeof' be transitive.

Created on 25 Jan 2018  路  2Comments  路  Source: microsoft/TypeScript



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:

Awaiting More Feedback Suggestion

Most helpful comment

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.

All 2 comments

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?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MartynasZilinskas picture MartynasZilinskas  路  3Comments

uber5001 picture uber5001  路  3Comments

dlaberge picture dlaberge  路  3Comments

siddjain picture siddjain  路  3Comments

weswigham picture weswigham  路  3Comments