镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

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

Description

@KSXGitHub

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:

Activity

  1. MartinJohns commented on May 2, 2018

    @MartinJohns
    Contributor

    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

  2. ghost added
    DuplicateAn existing issue was already created
    on May 2, 2018
  3. typescript-bot commented on May 16, 2018

    @typescript-bot
    Contributor

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

  4. locked and limited conversation to collaborators on Jul 31, 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

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions