1

The following code will always produce an error, but as a sketch, this is what I aim to represent:

interface A  {
    [ key : string ] : string, 
    "anotherKey" : MyInterface
}

I've checked a few books, TS documentation, tested in ts-node, but I am not that well versed and need some help.

How can I specify an object whose most keys are "key":"value" but some specific aren't?

Minsky
  • 2,277
  • 10
  • 19

1 Answers1

1

Use a regular type and intersection:

type MySpecialType = {
    specific: { type: number; };
    extremely: { specific: { type: string; } };
} & {
    [key: string]: string;
};

& is read as and

So this is saying this is a really specific type and an index signature of strings to strings.

kelsny
  • 23,009
  • 3
  • 19
  • 48
  • shouldn't it be `|` – Minsky Mar 17 '22 at 20:08
  • No because you want to say that it has specific properties *and* an index signature, like I said above. You don't want it to be `|` which is union, read as *or*. – kelsny Mar 17 '22 at 20:23
  • Please review https://stackoverflow.com/questions/61431397/how-to-define-typescript-type-as-a-dictionary-of-strings-but-with-one-numeric-i to and the part of the answer that starts "One common workaround to the lack of rest index signatures...". Intersections like this are technically impossible (the type of the `specific` property should be `string & {type: number}` and there are no values of that type) and weird things happen when you try to actually use one of these types. – jcalz Mar 17 '22 at 20:38