Skip to content

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

Closed

Description

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

Activity

  1. RyanCavanaugh commented on Apr 3, 2017

    @RyanCavanaugh
    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.

  2. RyanCavanaugh commented on Jul 22, 2020

    @RyanCavanaugh
    Member

    This works now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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