Skip to content

Allow for indexable types other than string and number #19538

Closed
@aryzing

Description

@aryzing

Given the following definition of a user and a user map,

type UserId = string;

interface User {
  id: UserId;
  name: string;
  email: string;
}

interface UserMap {
  [id: string]: User;
}

let userMap: UserMap = {
  id0001: {
    id: 'id0001',
    name: 'person1',
    email: '[email protected]',
  },
};

We can insert another user into the map by using a variable of type UserId,

let anotherUserId: UserId = 'id0002';

userMap[anotherUserId] = {
  id: anotherUserId,
  name: 'person2',
  email: '[email protected]',
}

However, I was surprised to find out that the indexable type can't be defined using the UserId type,

interface UserMap {
  [id: UserId]: User // error!
}

I'm sure we would all appreciate the certainty of knowing that the value we're using as an index is of the proper type, to avoid situations like

let productId: ProductId = 'prod123'

userMap[productId] = {/*...*/}

Is this a viable feature to include in TypeScript?

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