zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] 120. Hard - ObjectFromEntries

typescript Hard 120
2023-09-14 08:59:11 时间

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>>,
]