// 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