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

TypeScript shouldn't assume {[name: string]: NonUndefinedType} has no undefined properties #23817

Closed
KSXGitHub opened this issue May 2, 2018 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@KSXGitHub
Copy link
Contributor

TypeScript Version: 2.8.3

Search Terms: object type undefined

Code

interface Foo {
    [_: string]: number
}

const foo: Foo = {}

// foo.abc is undefined, but TypeScript allows this
foo.abc.toString()

Expected behavior:

Object is possibly undefined

Actual behavior:

TypeScript allows it

Playground Link: link

Related Issues:

@MartinJohns
Copy link
Contributor

MartinJohns commented May 2, 2018

This is a known issue and is unfortunately "as intended", see #9235, #13161, #12287, and #7140. It's the same reason why accessing arrays by index does not result in a possibly undefined type, even tho theoretically the array could be empty. You'd need to add security checks basically at every indexer and array access, which would add a lot of bloat code to cases where usually you know beforehand that you have a value.

A common practice is to leave it as it is when you know that you will always access known keys, or explicitly add undefined to your indexer type:

interface Foo {
    [_: string]: number | undefined;
}

There's still an open proposal to add a compiler flag to automatically mark such indexers as undefined with an additional strict-flag: #13778

@ghost ghost added the Duplicate An existing issue was already created label May 2, 2018
@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@microsoft microsoft locked and limited conversation to collaborators Jul 31, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants