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
and:
- Create
UserKeyas the union ofUser's keys - Create
getUserProperty(user, key)that returns the value at that key, withkeyconstrained toUserKey - Create
Configfrom the existingconfigvalue, andConfigKeyfromConfig's keys - Preserve literal types on
httpMethods, then createHttpMethodfrom that array - Create
makeRequest(method, url)that returns a string like"GET /api/users" - Export
getUserProperty,makeRequest,config, andhttpMethods
Completion checks:
getUserProperty({ id: '1', name: 'Alice', email: 'a@b.com', age: 30 }, 'name')β'Alice'makeRequest('GET', '/api/users')β'GET /api/users'config.apiUrlstays'https://api.example.com'andconfig.timeoutstays5000