Typescript-从类型的数组转换为类型的对象



我需要这种类型的

type Sample = [a: string, b: number]

转换为

type Sample2 = { a:string, b:number}

我需要它以对象的形式在参数中心传递函数的参数

function example(otherFunctionParameters: Parameters<typeof otherFunction>){}

我不想在参数中传递数组。

我怎样才能做到这一点?

因为您不能在类型系统中操作元组标签,所以您能做的最好的事情就是手动提供一个属性键元组,原始函数中的每个参数都有一个。

通过根据jcalz的回答改编一些实用程序,这里有一个通用实用程序,它将为函数中的参数提供一个映射对象:您为每个参数提供函数类型和标签元组:

TS游乐场

type ZipTuples<Keys extends readonly any[], Values extends readonly any[]> = {
[K in keyof Keys]: [Keys[K], K extends keyof Values ? Values[K] : never];
};
type ZipTuplesAsObject<
Keys extends readonly PropertyKey[],
Values extends readonly any[],
> = { [T in ZipTuples<Keys, Values>[number] as T[0]]: T[1] };
type ParamsAsObject<
Fn extends (...params: readonly any[]) => any,
Keys extends readonly PropertyKey[],
> = ZipTuplesAsObject<Keys, Parameters<Fn>>;

// Use
declare function otherFunction (
irrelevantLabel: string,
alsoNotUsed: number,
onlyTheTypesMatter: boolean,
): void;
function example (objectParam: ParamsAsObject<typeof otherFunction, ['a', 'b', 'c']>) {
// objectParam; // { a: string; b: number; c: boolean; }
const {a, b, c} = objectParam;
a; // string
b; // number
c; // boolean
}

最新更新