Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make sure a string literal union belongs to an object's keys

Tags:

typescript

export type A = "a" | "b" | "c";

const obj = { a: 4, b: 5, c: 6, d: 7 };

How do I make sure all elements of A are keys of object obj?

like image 364
hi-im-green-pattern Avatar asked Oct 17 '25 16:10

hi-im-green-pattern


1 Answers

Depends on what you need, you can automatically construct your type:

All keys as a type

You can use keyof to have all the keys as a union. Since keyof needs to be used on a type, the keyof typeof obj:

const obj = { a: 4, b: 5, c: 6, d: 7 };

export type A = keyof typeof obj; // "a" | "b" | "c" | "d"

Playground Link

Remove some of the keys

You can then Exclude some of the keys and get the rest:

const obj = { a: 4, b: 5, c: 6, d: 7 };
type AllKeys = keyof typeof obj;
export type A = Exclude<AllKeys, "d">; // "a" | "b" | "c" 

Playground Link

the AllKeys type is just for convenience, you can inline it and use Exclude<keyof typeof obj, "d">

Only allow some of the keys

This would be sort of the opposite of Exclude - instead of blacklisting keys, you have a whitelist and only pick keys that exist in it using an intersection:

const obj = { a: 4, b: 5, c: 6, d: 7 };
type AllKeys = keyof typeof obj;
type AllowedKeys = "a" | "b" | "c" | "y" | "z";
export type A = AllKeys & AllowedKeys; // "a" | "b" | "c"

Playground Link

Again, the two types AllKeys and AllowedKeys are here for convenience. You can also have the same as keyof typeof obj & ("a" | "b" | "c" | "y" | "z");

like image 155
VLAZ Avatar answered Oct 20 '25 18:10

VLAZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!