#Making an object with "generic keys"

1 messages · Page 1 of 1 (latest)

livid wharf
#

CC: @vocal hornet

I have an object which is a plain record type (it must be a plain record type, since it is the result of parsing a user-supplied plain-text file). However, there are some keys that, when checked and accessed, should be one type instead of another. For example:

type MyRecord = {
    [string]?: string,
    ['Foo' | 'Bar' | 'Baz']?: string[],
};

const x: MyRecord = someFunc();
if (x['Test']) // any key is a string, if defined:
    console.log(x['Test'].toUpperCase());
if (x['Foo']) // any of the specific keys make it an array:
    console.log(x['Foo'].map(s => s.toUpperCase());

Might be worth noting that the union is coming from an ['...', '...'] as const.

#

NEVERMIND I GOT IT lol

#

Literally right after posting

#

Intersection types 😎

#

wait no I didn't

#

wait yes I did

#

as const is necessary cuz otherwise (typeof arr)[number] is just string so you get string & string[] which is not very useful