Skip to content

Arrays can be treated as string-indexable types  #17191

Description

TypeScript Version: 2.4.0
Code

const foo: { [index: string]: any } = [42];

Expected behavior:
The code above doesn't compile.

Actual behavior:
Typescript silently accepts such code.

Activity

  1. RyanCavanaugh commented on Jul 14, 2017

    @RyanCavanaugh
    Member

    You can think of it this way - for the purposes of indexing, number is a subtype of string due to how JavaScript works

  2. JRGranell commented on Jul 14, 2017

    @JRGranell

    Ryan Cavanaugh (@RyanCavanaugh) - could this be addressed in strict-mode?

    In strict mode, not all JS is a valid TS (e.g. no implicit any), therefore this presents an opportunity to discourage const foo = {'42': 'foo'}; const bar = foo[42] in favour of stricter typings.

    Alternatively I would be interested in in other approaches or workarounds given that assigning an array to what is expected to be an object could have significant issues at run-time.

  3. RyanCavanaugh commented on Jul 14, 2017

    @RyanCavanaugh
    Member

    Arrays are objects.

  4. locked and limited conversation to collaborators on Jun 14, 2018
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

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions