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

Type guards don't work on key/value objects #14957

Closed
diestrin opened this issue Mar 31, 2017 · 2 comments
Closed

Type guards don't work on key/value objects #14957

diestrin opened this issue Mar 31, 2017 · 2 comments
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript

Comments

@diestrin
Copy link

diestrin commented Mar 31, 2017

TypeScript Version: 2.2.2 with --strictNullChecks

Code

let test: string;

const obj1: {val: string|number} = {val: ''};
if (typeof obj1.val === 'string') {
  test = obj1.val; // => Works fine
}

const obj2: {[k: string]: string|number} = {val: ''};
if (typeof obj2.val === 'string') {
  test = obj2.val; // => Type 'string | number' is not assignable to type 'string'
}

Expected behavior:
Type guards to work on key/value objects

Actual behavior:
Can't infer the correct type after check

@RyanCavanaugh RyanCavanaugh added In Discussion Not yet reached consensus Suggestion An idea for TypeScript labels Apr 3, 2017
@RyanCavanaugh
Copy link
Member

Interesting. This will likely require some architectural changes as we currently have no symbol to associate with the .val property access and thus nothing to narrow by.

@RyanCavanaugh
Copy link
Member

This works now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants