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
?
Depends on what you need, you can automatically construct your 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
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">
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With