juan garcia
juan garcia

Reputation: 1516

How to define a type of typescript with a variable number of keys?

I have the following case I don't know exactly how to express in typescript:

{
  "things": {
    "a": 11,
    "b": 22,
    .
    .
    .
  }
}

Then I would like to define something like:

type Response<T> = { [_: string]: T }

So the type above represents any response with a key and a certain value of type T, but I will have many keys like stated in the json, "a" "b"... and I don't find the type for it.

Upvotes: 8

Views: 3502

Answers (1)

Harshal Patil
Harshal Patil

Reputation: 20970

This should work:

interface Response<T> {

    things: {
        [key: string]: T;
    };
}

If you have certain keys fixed like a, you can do:

interface Response<T, R> {

    things: {
        // fixed keys
        a: R;
        // some more fixed keys.

        [key: string]: T;
    };
}

Upvotes: 14

Related Questions