TypeScript | Type Keys and Values as Type
type Status = {
all: 0
active: 1
inactive: 2
}
// 'all' | 'active' | 'inactive'
type StatusText = keyof Status
// 0 | 1 | 2
type StatusNumber = Status[StatusText]
// Good
const statusText: StatusText = 'active'
const statusNumber: StatusNumber = 0
// Bad
const wrongStatusText: StatusText = 'possible'
const wrongStatusNumber: StatusNumber = 3
Now one can reuse the initial type definition instead of hard-coding a new type with the same values twice.
Playground example.