首页 > 解决方案 > 无法将数组原型扩展应用于 TypeScript 中的只读数组

问题描述

这是TypeScript 中 Object.fromEntries() 结果的 Infer shape 的延续,尽管您可能不需要阅读它就知道发生了什么。

如果数组是正确的形状,我正在尝试扩展Array原型以添加快捷方式。Object.fromEntries()

// the aforementioned question uses this signature for Object.fromEntries() replacing `this` 
// with a parameter `array`
interface Array<T> {
  objectFromEntries<
    P extends PropertyKey,
    A extends ReadonlyArray<readonly [P, any]>
  >(this: A): { [K in A[number][0]]: Extract<A[number], readonly [K, any]>[1] };
}

如果数组不是readonly但它的元素是,这很好用,但不适用于数组的只读元组。

const works = [['a', 1] as const, ['b', 2] as const];
let obj = works.objectFromEntries();

const doesntWork = [['a', 1], ['b', 2]] as const;
obj = doesntWork.objectFromEntries();
/**
 * Error message:
 *   Property 'objectFromEntries' does not exist on type 'readonly [readonly ["a", 1], readonly ["b", 2]]'. ts(2339)
 */

我尝试过A与一堆变体结合,但它们都不起作用。

    objectFromEntries<
      P extends PropertyKey,
      A extends
        ReadonlyArray<readonly [P, any]> |
        Array<readonly [P, any]> |
        ReadonlyArray<[P, any]> |
        Array<[P, any]> |
        readonly [...readonly [P, any][]]
    >(this: A): { [K in A[number][0]]: Extract<A[number], readonly [K, any]>[1] };

想法?

TS游乐场

标签: arraystypescript

解决方案


解决方案简单明了。我还需要添加该方法ReadonlyArray<T>


推荐阅读