0

I want to create a type which is a Map has all possible literals of a string literal union type.

For example:

type TNumberNames =
  | 'one'
  | 'two'
  | 'three'

const numberMap: MyMapType = new Map().set('one', 1).set('two', 2).set('three', 3);
// this Map object should have all literals in TNumberNames!

I already found a way in Object instead of Map:

const numberRecord: Record<TNumberNames, number> = {
  one: 1,
  two: 2,
  three: 3,
};

in above example, if three is removed in numberRecord, TS compiler shows an error.

How do I declare MyMapType to do like this for Map object?

jcalz
  • 264,269
  • 27
  • 359
  • 360
  • you can declare a map like `const map = new Map<"a" | "b" | "c", number>()` but it will never be *required* to have a value for each key. – Tobias S. Nov 24 '22 at 09:52
  • I am going to replace `Required` with just `TNumberNames` in your example; `Required<>` isn't doing what you think it's doing here, and leaving it this way is distracting from your question. – jcalz Nov 25 '22 at 03:04
  • What do you plan to do with such a `RequiredMap` type? One could possibly implement that like [this](https://tsplay.dev/w8BvVm)... does that meet your needs? If so I could write up an answer explaining; if not, what am I missing? – jcalz Nov 25 '22 at 03:07

0 Answers0