Skip to content

Latest commit

 

History

History
37 lines (31 loc) · 1.08 KB

extract-object-type-keys-into-a-union-type.md

File metadata and controls

37 lines (31 loc) · 1.08 KB

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.