Let’s say you have a role object like this:
const role = {
visitor: "visitor",
admin: "admin",
superAdmin: "super-admin",
};
and we want to derive the object values as a type, we can do it like this
const role = {
visitor: "visitor",
admin: "admin",
superAdmin: "super-admin",
} as const;
type Role = (typeof role)[keyof typeof role]; // "visitor" | "admin" | "super-admin"
as const
allows us to infer the most specific type for a value. In this case, the type of role
is inferred as {visitor: "visitor", admin: "admin", superAdmin: "super-admin"}
instead of {visitor: string, admin: string, superAdmin: string}
, and it does this by making all the properties readonly.
Now to extract the object values as a type, we use the typeof
operator to get the type of the object, and then we use the keyof
operator to get the union of the keys of the object, and finally we use the indexed access operator []
to get the type of the values of the object.
I hope you find this useful, if you have any suggestions or questions, feel free to reach out to me on Twitter or LinkedIn.