【问题标题】:Getting type intersection of unknown number of objects in an array in TypeScript在 TypeScript 中获取数组中未知数量对象的类型交集
【发布时间】:2020-07-17 17:31:42
【问题描述】:

一个类似的问题has been asked,但我觉得它并没有完全回答我的问题。

如果我们有一个未知 shape 和未知 length 的对象数组,是否可以使用 TypeScript 创建它们类型的交集?

举个例子,如果我们有一个函数来获取对象并将这些对象合并为一个。

function merge(objects: any[]) {
  return objects.reduce((acc = {}, o) => Object.assign(acc, o));
}

const mergedObject = merge([
  { foo: "something" },
  { foo: "something else" },
  { bar: 100 },
  { bar: 500, baz: false },
]);

我们如何才能为这个函数创建一个返回类型,记住函数可以传递任意数量的具有不同属性的对象?

我可以预见到会做一个有限的版本,带有一定数量的通用参数,如下所示:

function merge<A, B, C, D, E, F, G>(
  objects: [A, B?, C?, D?, E?, F?, G?]
): A & B & C & D & E & F & G {
  return objects.reduce((acc = {} as any, o) => Object.assign(acc, o)) as any;
}

虽然这很愚蠢,但它确实为我们提供了自动完成和类型检查,但它最多只能处理一定数量的对象,而且似乎应该有更好的方法来做到这一点。

有什么方法可以很好地输入这个吗?当然假设函数的输入是静态的,如示例所示。

【问题讨论】:

    标签: typescript generics intersection


    【解决方案1】:

    有什么方法可以很好地输入这个

    不。事实上,这里是来自TypeScript sourcecodeObject.assign 的签名(它在4 个参数后放弃):

    /**
     * Copy the values of all of the enumerable own properties from one or more source objects to a
     * target object. Returns the target object.
     * @param target The target object to copy to.
     * @param source The source object from which to copy properties.
     */
    assign<T, U>(target: T, source: U): T & U;
    
    /**
     * Copy the values of all of the enumerable own properties from one or more source objects to a
     * target object. Returns the target object.
     * @param target The target object to copy to.
     * @param source1 The first source object from which to copy properties.
     * @param source2 The second source object from which to copy properties.
     */
    assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
    
    /**
     * Copy the values of all of the enumerable own properties from one or more source objects to a
     * target object. Returns the target object.
     * @param target The target object to copy to.
     * @param source1 The first source object from which to copy properties.
     * @param source2 The second source object from which to copy properties.
     * @param source3 The third source object from which to copy properties.
     */
    assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
    
    /**
     * Copy the values of all of the enumerable own properties from one or more source objects to a
     * target object. Returns the target object.
     * @param target The target object to copy to.
     * @param sources One or more source objects from which to copy properties
     */
    assign(target: object, ...sources: any[]): any;
    

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 2021-02-07
      • 2022-09-30
      • 2019-05-15
      相关资源
      最近更新 更多