Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Various issues with Type Guards #7735

Closed
bcherny opened this issue Mar 30, 2016 · 3 comments
Closed

Various issues with Type Guards #7735

bcherny opened this issue Mar 30, 2016 · 3 comments

Comments

@bcherny
Copy link

bcherny commented Mar 30, 2016

type A = number
type B = string
type C = number|string

const cc: C[] = [1, 2, "a", "b"]

function isNumber(a): a is A {
    return typeof a === 'number'
}

// OK
const dd = []
for (let n = 0; n < cc.length; n++) {
  const d = cc[n]
  if (typeof d === 'number') {
    dd.push(d.toFixed())
  }
}

// OK
const ee = []
for (let n = 0; n < cc.length; n++) {
  const d = cc[n]
  if (isNumber(d)) {
    ee.push(d.toFixed())
  }
}

// NOT OK - property 'toFixed' does not exist on type 'number' | 'string'
// (guard fails when using "cc[n]" instead of first assigning to "d")
const ff = []
for (let n = 0; n < cc.length; n++) {
  if (typeof cc[n] === 'number') {
    ff.push(cc[n].toFixed())
  }
}

// NOT OK - property 'toFixed' does not exist on type 'number' | 'string'
// (guard fails when guarding the inverse)
const gg = []
for (let n = 0; n < cc.length; n++) {
  const d = cc[n]
  if (typeof d !== 'number') { continue }
  gg.push(d.toFixed())
}

// NOT OK - property 'toFixed' does not exist on type 'number' | 'string'
// (guard fails when used in a filter)
// @see https://github.com/Microsoft/TypeScript/issues/7657
const hh = cc
  .filter(isNumber)
  .map(c => c.toFixed())
@Arnavion
Copy link
Contributor

(1) is probably part of #3812

(2) is part of #2388 (continue is ignored for the purpose of narrowing in the rest of the loop body.)

(3) is #7657 as you already mentioned.

@RyanCavanaugh
Copy link
Member

Type guards are basically being completely rewritten, so we'll have to check these examples again later.

@bcherny
Copy link
Author

bcherny commented Mar 31, 2016

Sounds good. Will close this as a duplicate.

Getting this support in would be great, otherwise when this topic comes up around my scala friends I need to change the subject :neckbeard:

@bcherny bcherny closed this as completed Mar 31, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants