Skip to content

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

@diestrin

Description

@diestrin

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions