0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

3 Comments

It kind of works, altough I'm not really satisfied because the [key: string] value should not have the isReady property. :/
this is more of a conceptual mistake i'm doing right there, I should find an other solution
are you familiar with typescript utility types? typescriptlang.org/docs/handbook/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.