0

I have a typescript function, with multiple arguments, I would like to call with a single string. E.g. fn(a: string, b: number, c: boolean) {...}

For example, suppose I have let str: string = "a: 'A', b: 5, c: false"; Is there are a way (short of parsing this string) to call the function directly? Obviously just the call let result = fn(str) does not work.

Chris Joslin
  • 63
  • 1
  • 8

1 Answers1

2

Is there are a way (short of parsing this string) to call the function directly?

Short answer:

Nope.


Longer answer:

Javascript does not provide a good way to encode function and argument lists as strings.

You need to encode that data somehow as a string, and then decode that data into the right format to use the data it contains. You could encode it as JSON for instance:

const json = '{ "a": "A", "b": 5, "c": false }'
const { a, b, c } = JSON.parse(json)
fn(a, b, c)

But this means encoding/decoding that string according to your custom logic, which you said you don't want to do.


Bad answer:

Use eval:

const myEvilStr = "fn('A', 5, false)"
eval(myEvilStr)

This is interesting academically, but uh, yeah, don't do that. Ever.

Some reading on why not to do this, in case I haven't sold it:

what does eval do and why its evil?

Why is using the JavaScript eval function a bad idea?

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337