3

I'm trying to allow dynamic properties in my TS class like so.

export class Finding {
  id?: number;

  title = '';

  assets?: Asset[] = [];

  createdAt = Math.floor(Date.now() / 1000);

  [dynamicField: string]: DynamicFieldTypes;
}

But it gives me the following error.

Property ‘title’ of type ‘string’ is not assignable to ‘string’ index type ‘DynamicFieldTypes’.ts(2411) View Problem

I assume it's because [dynamicField: string] overrides the types of all other properties. How do I fix that?

Inheritance doesn't fix that either

link to playground

Alex Ironside
  • 4,658
  • 11
  • 59
  • 119
  • This is essentially a duplicate of https://stackoverflow.com/q/61431397/2887218 and there's no great approach. If you don't think this is a duplicate and don't want to see it closed as such, please [edit] the question to clearly distinguish between them. – jcalz Aug 04 '22 at 13:42
  • I usually use an intersection type for this with types. – Behemoth Aug 04 '22 at 13:43
  • @Behemoth what do you mean? – Alex Ironside Aug 04 '22 at 13:45
  • When using types you can create an intersection with `&` to *solve* this but it's something completely different with classes of course. – Behemoth Aug 04 '22 at 13:46
  • Yeah. That's what I thought. @jcalz my question is about classes, not types. It's not a duplicate – Alex Ironside Aug 04 '22 at 13:48
  • Does [this approach](https://tsplay.dev/NdAGQm) meet your needs? If so I could write up an answer explaining it; if not, what am I missing? – jcalz Aug 04 '22 at 14:02

0 Answers0