Reputation: 1858
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
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
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);
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