#Map with definite keys and values

7 messages · Page 1 of 1 (latest)

celest dust
#

How do I properly annotate a Map in TS? I want to specify the possible keys and its values like this:

type options = {
  foo?: 'black' | 'blue';
  bar?: 'smart' | 'very smart';
}
const o: Map<keyof options, options[keyof options]> = new Map();

seems not to work as expected

tidal rivet
#

you kinda can't, maps just aren't made for that

celest dust
#

weird. The problem seems to me that I can't use a generic that matches the key to the value

#

as I understand it keyof options is interpreted as possibly two different keys so the value is always all values

tidal rivet
#

see Record<keyof options, options[keyof options]> vs { [K in keyof options]: options[K] }
unfortunately, Map doesn't have something for the latter

celest dust
#

well, ok thank you

odd bay
#

nitpick:

const o = new Map<keyof options, options[keyof options]>();