首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法将数组原型扩展应用于TypeScript中的只读数组

无法将数组原型扩展应用于TypeScript中的只读数组
EN

Stack Overflow用户
提问于 2020-07-24 04:13:02
回答 1查看 98关注 0票数 1

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

我正在尝试扩展Array原型,以便在Object.fromEntries()周围添加一个快捷方式,前提是数组的形状适合它。

代码语言:javascript
运行
复制
// 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,但它的元素是只读的,这很好用,但不适用于数组的只读元组。

代码语言:javascript
运行
复制
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与一堆变体结合起来,但它们都不起作用。

代码语言:javascript
运行
复制
    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 Playground

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-24 14:57:24

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63062439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档