In TypeScript, we can use a Tuple of types to create typed named rest arguments. This is useful for rest arguments.
type Params = [myString: string, myNumber: number, mySecondString: string]
const fn = (...args: Params) => null
// Type is (myString: string, myNumber: number, mySecondString: string) => null
Is there any way to achieve the same when using a mapped tuple type?
type TypeMap = {
"string": string
"number": number
}
const inputs = [
{name: "myString", type: "string"},
{name: "myNumber", type: "number"},
{name: "mySecondString", type: "string"},
] as const
type InputToTuple<T extends typeof inputs> = { [P in keyof T]: TypeMap[T[P]["type"]] };
type Params = InputToTuple<typeof inputs>
const fn = (...args: ParamsIWant) => null
// Type is (args_0: string, args_1: number, args_2: string) => null
Is there any way to supply the names of these parameters when the Tuple is created as a mapped type?
The core is to make this line:
type InputToTuple<T extends typeof inputs> = { [P in keyof T]: TypeMap[T[P]["type"]] };
Produce this result:
type Params = InputToTuple<typeof inputs>
// Type is [myString: string, myNumber: number, mySecondString: string]
Is this possible at all?
A note about why: I am building a way to let TypeScript infer types based on an Ethereum JSON ABI (and using as const
to get type narrowing). This works perfectly for everything except named parameters.