#Dynamic Function Arguments

14 messages · Page 1 of 1 (latest)

sour orchid
#

Let's say I have this:

declare function makeFunction(...args: FunctionArgs): void;
const test_me = makeFunction;
test_me("sad", "asdas");```

If I type `test_me(` it will give me auto completion that I have two parameters `a` and `b`.

How can I implement this in the case where I have a string `s = "a is ${a} b is ${b}` and I want to have something like:

s = "a is ${a} b is ${b}
type FunctionArgs = [extract the parameters between {} from s];
declare function makeFunction(...args: FunctionArgs): void;
const test_me = makeFunction;
test_me("sad", "asdas");```

I have these strigns from which I want to extract what arguments a function should have. They are all know at compile time. Is this possible?

wheat hemlock
#

Not the labels, because tuple labels are not manipulatable on type level.

#

You can get [string, string] out of it though so you know it needs 2 arguments, you just can't get the argument names.

#

If the names are very important then you can consider an API of test_me({ a: 'hello', b: 'world' }) instead.

sour orchid
#

With the API approach would writing test_me( give me auto completion for {a,b}?

wheat hemlock
#

Yeah.

sour orchid
#

Would it be too much to ask for an example implementation for both cases you proposed?

urban spokeBOT
#
nonspicyburrito#0

Preview:```ts
type ExtractTemplateKey<T> =
T extends ${string}\$\{${string}\}${infer R}
? [string, ...ExtractTemplateKey<R>]
: []

function fn(
...args: ExtractTemplateKey<"a is ${a} b is ${b}">
) {}

fn
// ^?```

#
nonspicyburrito#0

Preview:```ts
type ExtractTemplateKey<T> =
T extends ${string}\$\{${infer K}\}${infer R}
? K | ExtractTemplateKey<R>
: never

function fn(
options: Record<
ExtractTemplateKey<"a is ${a} b is ${b}">,
string

) {}

fn({}) // <- trigger autocomplete here```

sour orchid
#

Thanks for all the help! 🙂

#

!resolved

#

I do not know what the little basket icons mean. Do I need to give you some credit/score?

wheat hemlock
#

Oh if you mean the 🗑️ react, that's for telling the bot to delete the message.

#

There is a reputation system in the Discord but eh, I personally don't care that much about it.