-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Description
16259 - ToPrimitive
MUST WATCH this one: ToPrimitive. The problem itself isn't that interesting to be honest, but there's one extremely amazing solution I found that is absolutely transcendent! So exciting!
🎥 Video Explanation
🔢 Code
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
const sym = Symbol('a');
type A1 = ToPrimitive<{
name: 'Tom';
age: 30;
married: false;
addr: {
home: '123456';
phone: '13111111111';
};
bigint: 1n;
symbol: typeof sym;
hobbies: ['sing', 'dance'];
}>;
type B1 = {
name: string;
age: number;
married: boolean;
addr: {
home: string;
phone: string;
};
bigint: bigint;
symbol: symbol;
hobbies: [string, string];
};
type C1 = Expect<Equal<A1, B1>>;
// ============= Your Code Here =============
type ToPrimitive<T> =
T extends number ? number
: T extends string ? string
: T extends boolean ? boolean
: T extends bigint ? bigint
: T extends symbol ? symbol
: T extends null ? null
: T extends undefined ? undefined
: T extends object
? { [P in keyof T]: ToPrimitive<T[P]> }
: never;
// @BOCbMOU (first GitHub issue ever! wow!)
type ToPrimitive<T> =
T extends object
? {
[P in keyof T]: ToPrimitive<T[P]>
}
: T extends { valueOf: () => infer P }
? P
: T;
// ================== NOPE ==================
type ToPrimitive<T> = {
[K in keyof T]: T[K] extends string
? string
: T[K] extends number
? number
: T[K] extends boolean
? boolean
: ToPrimitive<T[K]>
}➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
No labels