1

I'm trying to define an interface with keys that will always be there (bar and baz) and also preserve the possibility of having other arbitrary keys as well.

Example of an object that I'm trying to write an interface for:

{ 
  "bar": "ABC", 
  "baz": 10, 
  "something-something": true 
}

Example of a desired interface (which doesn't really work):

interface Foo {
  // pre-defined keys
  bar: string;
  baz: number;

  // other arbitrary keys
  [key: string]: boolean;
}

The error I'm getting for the above interface:

TS2411: Property 'foo' of type 'string' is not assignable to string index type 'boolean'.

Rewriting the interface into a type and separating "mandatory" keys from the "arbitrary" ones doesn't work either:

type Foo2 = {
  foo: string;
  bar: number;
} & { [key: string]: boolean };

How can this be achieved?

Alex Lomia
  • 6,705
  • 12
  • 53
  • 87
  • 1
    There's no good way to say "all properties *except* `foo` and `bar` will be of type `boolean`". See the linked question/answers for the various approaches and workarounds. Your `Foo2` type works for some use cases but not all. – jcalz Jul 31 '23 at 18:21

0 Answers0