1

I would like to create a type that defines one static property and where other properties will have a different signature:

type Spec = {
  [K in string]: K extends "foo"
    ? string
    : string[];
};

const spec: Spec = {
  foo: 'a',
  bar: ['a'],
  baz: ['b']
}

Apparently, the type checker ignores K extends "foo" restriction and wants foo property to be an array of strings instead of a string.

How can I solve that?

aiven715
  • 89
  • 1
  • 1
  • 8
  • @Terry Unfortunately OP's type's properties don't have the same type, so they can't actually use the workarounds described in that question. Howevere, [here](https://tsplay.dev/wQxMZW) are two of the most common workarounds for when the types are different (in this case its `string` and `string[]`); a generic validating helper function, and changing the type of the object. – kelsny Sep 15 '22 at 18:51
  • @Terry thanks, that describes a similar issue but with a few differences: I don't know additional properties upfront (they should be dynamic) and they should have different types (string and string[]) whereas type in a mentioned question defines all properties as string. – aiven715 Sep 15 '22 at 18:52
  • Yeah, there's no specific type that works this way, which is unfortunate. See the answer to the linked question for workarounds and consider giving [ms/TS#17867](https://github.com/microsoft/TypeScript/issues/17867) a – jcalz Sep 15 '22 at 20:24

0 Answers0