Skip to content

Arrays can be treated as string-indexable types #17191

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

Closed
kujon opened this issue Jul 14, 2017 · 3 comments
Closed

Arrays can be treated as string-indexable types #17191

kujon opened this issue Jul 14, 2017 · 3 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@kujon
Copy link
Contributor

kujon commented Jul 14, 2017

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.

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Jul 14, 2017
@RyanCavanaugh
Copy link
Member

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

@JRGranell
Copy link

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

@RyanCavanaugh
Copy link
Member

Arrays are objects.

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

3 participants