ToPrimitive
Less than 1 minuteTC-Medium
ToPrimitive
Problem
Convert a property value recursively into a primitive type.
type X = {
name: 'Tom',
age: 30,
married: false,
info: {
additional1: null,
additional2: undefined
}
}
type Expected = {
name: string,
age: number,
married: boolean,
info: {
additional1: null,
additional2: undefined
}
}
type Todo = ToPrimitive<X> // ExpectedSolution
type ToPrimitive<T> =
T extends object
? T extends (...args: any[]) => any
? Function
: { [K in keyof T]: ToPrimitive<T[K]> }
: T extends string
? string
: T extends number
? number
: T extends boolean
? boolean
: T extends symbol
? symbol
: T extends bigint
? bigint
: THow it works:
- If
Tis a function, map it toFunction. - If
Tis an object (non-function), recursively map each property. - For primitives, widen the literal type to its base primitive (
'Tom'→string,30→number, etc.). nullandundefinedfall through toTunchanged.
Key Takeaways
- Check for function before checking for object because functions satisfy
T extends object. - The chain of primitive checks (
extends string ? string : ...) widens literal types to their base. nullandundefineddo not extendstring | number | boolean | symbol | bigint, so they are returned as-is.
