如何在Typescript中获取类型化的Object.entries()和Object.fromEntries?

jpfvwuh4  于 2023-05-08  发布在  TypeScript
关注(0)|答案(2)|浏览(198)

当我在typescript中为类型化/常量entries数组或objt对象使用Object.fromEntries(entries)Object.entires(obj)时,我将类型丢失为any或宽类型。
我可以手动分配泛型类型(例如Record<string, number>),但设置每对/密钥的类型是繁琐的。
这是我想要的一个例子。

类型化对象.fromEntries(entries)

const myArrayOfPairs = [["a", 5], ["b", "hello"], ["c", false]] as const;

// The type of the following is "any"
const myTypelessObject = Object.fromEntries(myArrayOfPairs);

// I want the type of this one to be: { a: 5; b: "hello"; c: false; }
const myTypedObject = createTypedObjectFromEntries(myArrayOfPairs);

类型化Object.entries(obj)

const myOldObject = {
    x: 6,
    y: "apple",
    z: true
};

// The type of the following is [string, string | number | boolean][]
const myEntries = Object.entries(myOldObject);

// I want the type of this one to be more specific.
// i.e.: (["x", number] | ["y", string] | ["z", boolean])[]
const myTypedEntries = getTypedObjectEntries(myOldObject);
kg7wmglp

kg7wmglp1#

Object.Entries(obj)-- Object to Array of KeyValue对

这个比较简单。使用[K in keyof OBJ_T]可以得到键,OBJ_T[K]给出相对值。
下面是它的一个简单实现:

// ~~~~~~~~~~~~~~~~~~~~~~~~ Utils ~~~~~~~~~~~~~~~~~~~~~~~~

type ObjectType = Record<PropertyKey, unknown>;
type PickByValue<OBJ_T, VALUE_T> // From https://stackoverflow.com/a/55153000
    = Pick<OBJ_T, { [K in keyof OBJ_T]: OBJ_T[K] extends VALUE_T ? K : never }[keyof OBJ_T]>;
type ObjectEntries<OBJ_T> // From https://stackoverflow.com/a/60142095
    = { [K in keyof OBJ_T]: [keyof PickByValue<OBJ_T, OBJ_T[K]>, OBJ_T[K]] }[keyof OBJ_T][];

// ~~~~~~~~~~~~~~~~~~~~ Typed Function ~~~~~~~~~~~~~~~~~~~~

function getTypedObjectEntries<OBJ_T extends ObjectType>(obj: OBJ_T): ObjectEntries<OBJ_T> {
    return Object.entries(obj) as ObjectEntries<OBJ_T>;
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~ Test ~~~~~~~~~~~~~~~~~~~~~~~~~

const myOldObject = {
    x: 6,
    y: "apple",
    z: true
};

const myTypelessEntries = Object.entries(myOldObject); // type: [string, string | number | boolean][]

const myTypedEntries = getTypedObjectEntries(myOldObject);
type myTypedEntiresType = typeof myTypedEntries;  // type: (["x", number] | ["y", string] | ["z", boolean])[]

TSPlayground。注意需要es2019作为Configs的目标。

Object.fromEntries(entries)--Object的键值对数组

这是一个更有挑战性的问题。
您需要首先使用infer提取内部数组对,然后使用公共UnionToIntersection实用程序类型合并结果。
这是我能想到的最好的:

// ~~~~~~~~~~~~~~~~~~~~~~~~ Utils ~~~~~~~~~~~~~~~~~~~~~~~~

// Data Types
type EntriesType = [PropertyKey, unknown][] | ReadonlyArray<readonly [PropertyKey, unknown]>;

// Existing Utils
type DeepWritable<OBJ_T> = { -readonly [P in keyof OBJ_T]: DeepWritable<OBJ_T[P]> };
type UnionToIntersection<UNION_T> // From https://stackoverflow.com/a/50375286
    = (UNION_T extends any ? (k: UNION_T) => void : never) extends ((k: infer I) => void) ? I : never;

// New Utils
type UnionObjectFromArrayOfPairs<ARR_T extends EntriesType> =
    DeepWritable<ARR_T> extends (infer R)[] ? R extends [infer key, infer val] ? { [prop in key & PropertyKey]: val } : never : never;
type MergeIntersectingObjects<ObjT> = {[key in keyof ObjT]: ObjT[key]};
type EntriesToObject<ARR_T extends EntriesType> = MergeIntersectingObjects<UnionToIntersection<UnionObjectFromArrayOfPairs<ARR_T>>>;

// ~~~~~~~~~~~~~~~~~~~~~ Typed Functions ~~~~~~~~~~~~~~~~~~~~~

function createTypedObjectFromEntries<ARR_T extends EntriesType>(arr: ARR_T): EntriesToObject<ARR_T> {
    return Object.fromEntries(arr) as EntriesToObject<ARR_T>;
}

// ~~~~~~~~~~~~~~~~ Test for entries->object ~~~~~~~~~~~~~~~~~

const myArrayOfPairs = [["a", 5], ["b", "hello"], ["c", false]] as const;

const myTypelessObject = Object.fromEntries(myArrayOfPairs); // type: any

const myTypedObject = createTypedObjectFromEntries(myArrayOfPairs);
type myTypedObjectType = typeof myTypedObject; // type: { a: 5; b: "hello"; c: false; }

TSPlayground

guicsvcw

guicsvcw2#

现在,使用新的const Type Parameter在TypeScript 5上更容易实现这一点。

//
// Object.fromEntries
//

const typeSafeObjectFromEntries = <
  const T extends ReadonlyArray<readonly [PropertyKey, unknown]>
>(
  entries: T
): { [K in T[number] as K[0]]: K[1] } => {
  return Object.fromEntries(entries) as { [K in T[number] as K[0]]: K[1] };
};

const myObject = typeSafeObjectFromEntries([
  ["a", 5],
  ["b", "hello"],
  ["c", false],
]); // { a: 5; b: "hello"; c: false } ✅

//
// Object.entries
// (add const param for less broader types (ie. string -> "apple") -> const T extends Record<PropertyKey, unknown>)
//

const typeSafeObjectEntries = <T extends Record<PropertyKey, unknown>>(
  obj: T
): { [K in keyof T]: [K, T[K]] }[keyof T][] => {
  return Object.entries(obj) as { [K in keyof T]: [K, T[K]] }[keyof T][];
};

const myEntries = typeSafeObjectEntries({ x: 6, y: "apple", z: true });
// ["x", number] | ["y", string] | ["z", boolean])[] ✅
// with const param: (["x", 6] | ["y", "apple"] | ["z", true])[] ✅

TypeScript Playground

相关问题