1

I need to define a recursive interface with an optional property that has a dynamic key:

export interface IAnswerValueSet {
  [linkId: string]: {
    answerValueSet?: fhir4.ValueSet;
    answerValueSetUrl: string;

    [linkId: string]?: IAnswerValueSet;  // problem is here
  };
}

I'm getting two errors from the compiler:

Property or signature expected from `?:`

Member 'IAnswerValueSet' implicitly has an 'any' type.

If I use a known key for the nested IAnswerValueSet it works as expected, but I need the key to be dynamic.

How can I define this interface correctly?

Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
  • Is this just a typo? You can't make an "optional" index signature; remove the `?`. Index signatures are already "optional" in that they don't require any particular property of the index type to exist. Note that if you do that you'll probably immediately run into other issues, and your problem becomes the same as in [this question](https://stackoverflow.com/q/61431397/2887218). – jcalz Mar 28 '23 at 15:14
  • @jcalz Thanks. I've removed the option from the nested property, however as you indicated I'm now getting: `Property 'answerValueSet' of type 'ValueSet | undefined' is not assignable to 'string' index type 'IAnswerValueSet'` from the first property – Brandon Taylor Mar 28 '23 at 15:22

1 Answers1

0

Thanks @jcalz. The answer linked in the comments provided the answer:

export interface IAnswerValueSet {
  [linkId: string]: {
    answerValueSet?: fhir4.ValueSet;
    answerValueSetUrl: string;
  } & {
    [linkId: string]: IAnswerValueSet
  };
}
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144