BonAppetit111
BonAppetit111

Reputation: 13

How to define index signature for a type alias of a Map in Typescript?

If I have defined a type for a Map like this:

type MyCustomMap = Map<string, number>;

How can I add an index signature so that I can set key-values after creation? I have been able to do such thing with types that define different attributes such as:

type MyCustomObj = {
    [key: string]: any;
    something: string;
}

But I could not find a way to do it in above's case.

Upvotes: 1

Views: 837

Answers (1)

Przemyslaw Jan Beigert
Przemyslaw Jan Beigert

Reputation: 2486

I think you're looking for something like this:

type MyCustomObj<Key extends string | number, Value, Rest = {}> =
    Key extends string ? { [key: string]: Value } & Rest: { [key: number]: Value } & Rest;

And you can use it like that:

type Obj = MyCustomObj<string, number>;
type CustomObj = MyCustomObj<string, number, { key: boolean }>;

Playground

Upvotes: 1

Related Questions