这是Infer shape of result of Object.fromEntries() in TypeScript的延续,尽管您可能不需要阅读它就能知道发生了什么。
我正在尝试扩展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] };
想法?
发布于 2020-07-24 14:57:24
解决方案简单明了。我还需要将该方法添加到ReadonlyArray<T>
中。
https://stackoverflow.com/questions/63062439
复制相似问题