arrays - 无法将数组原型扩展应用于 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] };
想法?
解决方案
解决方案简单明了。我还需要添加该方法ReadonlyArray<T>
。
推荐阅读
- flutter - 颤振:布局期间对象被赋予无限大小
- angular - angular 8 如何在不同动作的父组件中多次使用组件
- powershell - 在 PowerShell 中获取打印机的驱动程序版本和打印机名称
- excel - 无法使用字符串值查找和删除行
- python - Tkinter OptionMenu 删除
- html - 在特定的wordpress之间编辑小部件“宽度”
- aws-xray - 对您控制的服务的传入和传出请求进行 X 射线检查是否值得?
- android - 如何让我的 WearOS 应用在 LockScreen 上运行?
- python - 使用 numba 的对数除法和对数减法之间的性能差异
- python - 不用安装就使用pycurl