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.


© 2022, built with Gatsby. Subscribe via RSS.
Crafted by John Darryl Pelingo
. All rights reserved.