KevinTale
KevinTale

Reputation: 1858

how to implement interface with variable key and define key at the sametime

I want to create an interface with a defined key, and also a variable key, like so :

interface Data {
  api?: {
    isReady: boolean;
  };
  [key: string]: string;
}

Which leads to an error : Property 'api' of type '{ isReady: boolean; }' is not assignable to string index type 'string'.

I understand that [key:string]: string says "every key of this interface should have a string as its value", which is not the case for api, so the error makes sense.

So, is this possible to create such an interface, with a clearly define key/value pair + a variable key at the same level?

Thanks

Upvotes: 0

Views: 207

Answers (2)

Antot
Antot

Reputation: 3964

The api property might have its own type:

interface Api {
  isReady: boolean;
};

Then, we can mix the typings for the variable part:

interface Data {
  api?: Api;
  [key: string]: string | Api;
}

Upvotes: 1

andrès coronado
andrès coronado

Reputation: 170

you maybe want to to create an object that looks like this:

 interface Data {
  api?: {
    isReady: boolean;
  };
  [key: string]: any;
}

const data: Data = { 'api': { isReady: false }, 'someText': 'text' };
console.log(data);

enter image description here

Although it looks like a good idea doing so, it may not be the case because in this way you loose Type-safety.

Upvotes: 1

Related Questions