1

Below I have an object with uses a dynamic key of string. I know there will never be overlap between the dynamic key and _meta in real use, but how can I explicitly tell typescript that _meta should always be treated as the object specified, rather than as Highlight?

type FullHighlighter = {
    _meta: { /* special object */ }
    [highlightID : string] : Highlight
}
// Property '_meta' of type 'string' is not assignable to 'string' index type 'Highlight'

For example I thought this might work, but it didn't:

type FullHighlighter = {
    _meta: { /* special object */ }
    [highlightID : Exclude<string, "_meta">] : Highlight
}

Thanks!

Pete
  • 510
  • 7
  • 12
  • 1
    Could you please provide more code? – Nullndr May 11 '22 at 08:58
  • oh sorry, is `[highlightId: stirng]` a property of type `FullHIghlighter`? – Nullndr May 11 '22 at 09:00
  • Yes there's not really much more than needed that wouldn't just add confusion. `FullHighlighter` and `Highlight` can be replaced with anything (ie, `Animal` and `number` respectively). The issue is `string` overlapping with `_meta` whereas I would like `_meta` to be an exception and have a different type than that specified in the `string` key type definition – Pete May 11 '22 at 09:04
  • It is partialy possible to do. See [this](https://tsplay.dev/m3yZbw). However, you should add prefix to each ID. If it is not allowed, you can use numbers for id, see [here](https://tsplay.dev/wXK6oW) – captain-yossarian from Ukraine May 11 '22 at 09:46
  • No, there is no specific type in TypeScript that works how you want. Please see the answer to the linked question for more information. – jcalz May 11 '22 at 17:07

0 Answers0