mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
1.1 KiB
1.1 KiB
Extract Object Type Keys Into A Union Type
The object type is a way of grouping types together to represent something more complex. For instance, it may be used to represent the types of events that a reducer can process.
interface GlobalReducerEvent {
ADD_TODO: {
text: string
}
LOG_IN: {
email: string
}
DELETE_TODO: {
todo_id: number
}
}
From this object type, I can extract a union type of the keys, perhaps as part of building a more useful type mapping.
This can be done with
keyof.
type EventTypes = keyof GlobalReducerEvent;
//=> 'ADD_TODO' | 'LOG_IN' | 'DELETE_TODO'
The keyof type operator extracts each key of the GlobalReducerEvent into a
union type. This can be mixed into other types in all sorts of interesting
ways.