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

Validate indexed properties #8620

Description

@Liero

When object is annotated with following definition:

interface Person {
  "Id": number
  "First Name": string,
  "Last Name": string,
}

I would like to access the "First Name" and "Last Name" properties in type safe manner.

var person : Person = { Id: 5, "First Name": "Lorem", "Last Name": "Ipsum" };
var firstName = person["First Name"]; //this is neither validated by compiler nor I get auto completion for the properties
var _undefined = person["undefined"]; //compiler does not complain.

similarly:

person["First Name"] = "Lorem"; //this is neither validated by compiler nor I get auto completion for the properties
person["undefined"] = "Ipsum"; //compiler does not complain.

I have tried experimenting with restricting index signature type:

interface Person {
  [key: "First Name" | "Last Name"]: string;
} 

however, it compiler complains:

An index signature parameter type must be 'string' or 'number'

Activity

  1. mhegazy commented on May 16, 2016

    @mhegazy
    Contributor

    The compiler does know that values of type Person have a property called First Name and that its type is string. see:

    image

    It also knows that all JavaScript objects can be indexed in using strings. For these it does not know the type of the property, so it gives it a type any.

    You can use --noImplicitAny flag to catch these cases and flag them as errors.

    image

    As for completion for the name, this will be supported by #8428.

  2. Liero commented on May 17, 2016

    @Liero
    Author

    ahh, ok. I thought --noImplicitAnyis related to unannotated variables and parameters, but person is annotated. Hmm, I would welcome if those two were splitted into two flags (e.g --noImplicitAny, --noImplicitIndex), but that's probably not gonna happen. Also the error message could be: "Property 'undefined' does not exists on type 'Person'.

  3. locked and limited conversation to collaborators on Jun 19, 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

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions