[Typescript] 120. Hard - ObjectFromEntries

Implement the type version of Object.fromEntries

For example:

interface Model {
  name: string;
  age: number;
  locations: string[] | null;
}

type ModelEntries = ['name', string] | ['age', number] | ['locations', string[] | null];

type result = ObjectFromEntries<ModelEntries> // expected to be Model
 
/* _____________ Your Code Here _____________ */

type ObjectFromEntries<T extends any[]> = {
  [Key in T as Key extends any[] ? Key[0] extends string ? Key[0]: never: never]: Key[1]
}

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

interface Model {
  name: string
  age: number
  locations: string[] | null
}

type ModelEntries = ['name', string] | ['age', number] | ['locations', string[] | null]

type cases = [
  Expect<Equal<ObjectFromEntries<ModelEntries>, Model>>,
]

 

posted @ 2022-11-28 15:54  Zhentiw  阅读(20)  评论(0编辑  收藏  举报