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.

1
  • 1
    You can use JSON format and stringify then JSON.parse the string. Probably use an array instead of an object. Commented Mar 1, 2021 at 18:26

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.