1

I have the following interface / type as shown below:

export interface Bar {
  title?: string;
  [key: string]: string;
}

export type Foo = {
  name: string;
} & {
  [key: string]: Bar;
};

And when I try to declare a variable like so:

const someObject: Foo = {
  name: 'John',
  city: {
    a: 'something',
  },
};

It gives me the error:

Type '{ name: string; city: { a: string; }; }' is not assignable to type 'Foo '. Type '{ name: string; city: { a: string; }; }' is not assignable to type '{ [key: string]: Bar ; }'. Property 'title' is incompatible with index signature. Type 'string' is not assignable to type 'Bar'.


Question:

How to create an interface to satisfy an object like:

const someObject: Foo = {
  name: 'John',
  randomProperty1: { a: 'a' },
  randomProperty2: { b: 'b' },
  // any number of 'Bar'
};
Henny Lee
  • 2,970
  • 3
  • 20
  • 37
  • There's no specific interface that works that way. See the [question this duplicates](https://stackoverflow.com/q/61431397/2887218) for more information. If I translate the code from [the answer](https://stackoverflow.com/a/61434547/2887218) here, I get [this code](https://tsplay.dev/wRJVxw), which should demonstrate the possibilities and their pros/cons. – jcalz Sep 09 '21 at 16:51

0 Answers0