1

Let's say I have a function:

function myFunc(name: string, age: number){ }

To obtain the parameters of a function type in a tuple, I do the following:

type TArgs = Parameters<typeof myFunc> // = [name: string, age: number]

Now I need to create an object type from this tuple as shown below:

type TObj = {
    name: string, 
    age: number
}

How can I do this?

2

1 Answer 1

1

As the Typescript Whisperers in the comments have pointed out, You Can't Do This. I am writing this answer to help other mortals like me who get confused by the Parameter<> utility's labeled tuple [name: string, age: number] output.

At first glance it seems we should be able to reverse engineer key-value pairs from the tooltip output [name: string, age: number].

Alas, no. After all [name: string, age: number] is a labeled version of the tuple [string, number]. Hopes dashed.

labels don’t require us to name our variables differently when destructuring. They’re purely there for documentation and tooling.

Here are some demonstrations: (Playground)

const iAmTArgs: TArgs = ["myString", 0] // Passes: type really is [string, number]

const iAmNotTArgs: TArgs = [0, 0] // Error, as expected: Type 'number' is not assignable to type 'string'

type NameArg = Parameters<typeof myFunc>[0] // string
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.