keyof and typeof

Keyof Typeof
πŸ‘¨β€πŸ’Ό Let's use keyof and typeof to create type-safe utilities.
const palette = {
	primary: '#222222',
	accent: '#ff6600',
}

type PaletteKey = keyof typeof palette

const sizes = ['sm', 'md', 'lg'] as const
type Size = (typeof sizes)[number]
🐨 Open
index.ts
and:
  1. Create UserKey as the union of User's keys
  2. Create getUserProperty(user, key) that returns the value at that key, with key constrained to UserKey
  3. Create Config from the existing config value, and ConfigKey from Config's keys
  4. Preserve literal types on httpMethods, then create HttpMethod from that array
  5. Create makeRequest(method, url) that returns a string like "GET /api/users"
  6. Export getUserProperty, makeRequest, config, and httpMethods
Completion checks:
  • getUserProperty({ id: '1', name: 'Alice', email: 'a@b.com', age: 30 }, 'name') β†’ 'Alice'
  • makeRequest('GET', '/api/users') β†’ 'GET /api/users'
  • config.apiUrl stays 'https://api.example.com' and config.timeout stays 5000

Please set the playground first

Loading "keyof and typeof"
Loading "keyof and typeof"