til / Pick with keyof typeof in TypeScript
In TypeScript, we might want to get the keys of an object as a type for some purpose.
const transportation = {
AIRPLANE: 'airplane',
BICYCLE: 'bicycle',
CAR: 'car',
TRAIN: 'train',
}
type TransportationType = keyof typeof transportation
// "CAR" | "BICYCLE" | "AIRPLANE" | "TRAIN"
If we want to limit the options, we can’t use the Pick utility directly on this type, even though it looks like we’ve created a string union.
type OnlyCarAndBicycle = Pick<TransportationType, 'CAR' | 'BICYCLE'>
// TypeScript error:
// Type '"CAR"' does not satisfy the constraint '...'
// Type '"BICYCLE"' is not assignable to type '...'
Instead, we should use typeof transportation
, filter our options, then use keyof
.
type OnlyCarAndBicycle = keyof Pick<typeof transportation, 'CAR' | 'BICYCLE'>
//"CAR" | "BICYCLE"