Skip to content

Validate indexed properties #8620

Closed
Closed
@Liero

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'

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