1

Is it possible to create a type that's an intersection of both a known object and an index signature?

In the code below the type should be something like: { a: string, [prop: string]: number }, such that a must always be a string, but any other properties must be of type number

type Foo<T> = T & Exclude<{ [prop: string]: number }, keyof T>
type Bar = { a: string }
type FooBar = Foo<Bar>

const fooBar1: FooBar = { a: 'hello', b: 1 } // should pass
const fooBar2: FooBar = { a: 'hello', b: 1, c: 'a' } // should fail
const fooBar3: FooBar = { a: 1, b: 1 } // should fail

code

jcalz
  • 264,269
  • 27
  • 359
  • 360
TrevTheDev
  • 2,616
  • 2
  • 18
  • 36
  • 1
    You can create that type of course but it doesn't do what you want. No specific type in TypeScript works that way, unfortunately. See the open issue at [ms/TS#17867](https://github.com/microsoft/TypeScript/issues/17867) and the answer to the linked question. – jcalz Mar 04 '23 at 03:32

0 Answers0