这是indexloc提供的服务,不要输入任何密码
Skip to content

16259 - ToPrimitive (🎥 Video Explanation and Solution) #25179

@dimitropoulos

Description

@dimitropoulos

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

Release Date: 2023-03-26 19:00 UTC

ToPrimitive

🔢 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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions