Can we preserve the original function header even after the typescript compilation process?

Typically, one can access function information by using the following method:

function someFunction(arg1, { a, b, c}){}

someFunction.toString()

... compile and run

//function someFunction(arg1, { a, b, c}){}

However, when TypeScript compiles the code, any function that contains deconstructed arguments will be replaced with _a:

function someOtherFunction(arg1, { a, b, c}){}

console.log(someOtherFunction.toString())

... compile and run

//function someOtherFunction(arg1, _a){}

Is there a way to retrieve the original deconstructed argument information while still utilizing TypeScript?

I've searched through the TS issue tracker, but couldn't find a straightforward solution. Nothing stood out upon initial search.

EDIT As I was attempting this with ts-node, the fix was adjusting both the target and module as described here: https://github.com/TypeStrong/ts-node/issues/678. This ensures that the compiled code remains es6 code which preserves the deconstruction!

Thank you all!

Answer №1

Executing the Function.prototype.toString() method will consistently display the compiled javascript code, which varies depending on your target environment as it impacts how the code is compiled. This characteristic is specific to runtime javascript and cannot be influenced by Typescript during compile time.

Consider this basic example:

function someFunction(
    arg1: string,
    { a, b, c }: {a: string, b: string, c: string}
){}
alert(someFunction.toString())

If the targeted environment is ES5 or earlier, destructuring assignment is not supported. Therefore, the compiler adapts the argument structure to achieve similar functionality without assuming compatibility with unsupported features.

Example with ES3 target (click Run)

Example with ES2015 target (click Run)


To address this issue, you can modify your target environment but ensure that it supports destructuring assignments. If you are compiling for older environments, invoking toString() will always retrieve the function body adjusted for your target environment's requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Despite having unique ids, two file input forms are displayed in the same div in the image preview

Running into a minor issue once again. It may not be the most eloquent query, but I'm genuinely stuck and in need of some assistance. I am attempting to showcase image previews of selected files in a file input form. I have a jQuery script that reads ...

What causes an error when attempting to map an array in React+Redux?

Every time I attempt to execute the following code: const nums = this.props.date.phoneNumbers.map( (num) => { <span>{ num }<br/></span> }) I encounter an error message that reads: An assignment or function call was expected, ...

Creating an HTML table for displaying information

I am currently working with the following code : { key: 'synch', label: this.$t('Synch'), formatter: value => { return value; } }, Utilizing data from an API, I have implemented the following logic: this.items ...

INSERT INTO only if Name and Location are NOT identical

I'm facing an issue with adding a record to my psql table only if it has a unique Name and Location. Currently, the code I have is able to insert a record if the entry doesn't already exist in the table (based on name or location). However, when ...

Issue with Web API and AJAX: Unable to retrieve resource, server returned status code 400

[HttpPost("Login")] public async Task<IActionResult> Login([FromBody] SigninViewModel formData) { MemberCredential membercredential = await db.MemberCredential.FirstOrDefaultAsync(t => t.MemberAccount.Equals(f ...

Stop the automatic deduction of union types while utilizing an indexed access type within a generic function

I am currently working on developing a TypeScript interface that can automatically infer the function signature inside an object based on the adjacent key's presence and type, aiming to create a more ergonomic and generic interface. Here is what I ha ...

I am interested in implementing a "slide up" effect for the "slide menu" when it loses focus

When I focus out of the asmenu class, I attempt to trigger a 'slide up' effect. However, if I select two checkboxes from the child elements within the asmenu class, the focusout event is still triggered. Ideally, I would like the 'slide up& ...

Module Augmentation for extending Material UI theme is not functioning as expected

I'm having trouble expanding upon the Theme with Material UI because an error keeps popping up, indicating that I am not extending it correctly. The error message states: Property 'layout' is missing in type 'Palette' but required ...

Challenges arise when trying to load CSS on an EJS page in conjunction with using res.redirect()

When using Express with EJS, my base route is set as follows: router.get("/", productsData.getProducts); The "productsData" is sourced from my controllers page and the code snippet within that page is as follows: exports.getProducts = (req, res, next) => ...

Imitate a worldwide entity with Jest and Typescript

I have a React component that utilizes the global object Routes provided by the Rails gem js-routes. My component is being tested with Jest's snapshot testing feature. The issue arises when trying to mock the Routes global object in the test to return ...

Discover the type of an object in TypeScript

I am searching for a method to create a "mapped" object type in TypeScript. Here are the typings I currently have: interface Factory<T>{ serialize: (val: T)=>void, deserialize: ()=>T, } interface MyDict{ [key: string]: Factory& ...

Adding HTML elements dynamically using jQuery: A how-to guide

My objective is to start with one element upon loading the page, and this element should have an ID of "something_O". When the user clicks on an add link, a new identical HTML element should be added underneath the existing element. The new element should ...

Create a conditional event callback in TypeScript for React

How can I specify an optional callback for Events in a React Typescript component? interface Props{ data: any handleClick?: ()=>void } const FunctionalComponent: React.StatelessComponent<Props> = (props) => { return ( < ...

How can one continue repeating a series in async.js until an unforeseen error arises?

Is it possible to continuously execute a series of tasks in async.js until an unexpected error occurs? For example: async.series([ function(callback) { // perform task }, function(callback) { // perform another task }, ...

"Present a continuous sequence of images in HTML to create a dynamic video-like experience

A PHP file has been created to extract images from a MySQL database and display them as a sequence of images that update every half second. Using the setInterval method in JavaScript, the page is refreshed every half second to display a new picture. $(doc ...

Encountering "Missing requests" error while executing npm run pactTest on PACT.io

Check out the Test Repo I created: https://github.com/leongaban/pact-io-js-test https://i.sstatic.net/JESkK.jpg Anticipated Outcome To generate a Pact file for my TotalPayout.test.pact.ts script, run npm run pactTest. Findings D, [#38238] DEBUG -- : { ...

Keep the link underlined until a different button is pressed

I need help with a webpage that displays a list of partners organized by categories. When clicking on sidebar categories, the link remains underlined. However, if you click anywhere else on the page, the link becomes inactive. CSS: button:hover { t ...

React - Show/Hide All items

I want to achieve the functionality of expanding or collapsing all containers with a single button click. To accomplish this, I have created a new component called CollapsiblePanel using reactstrap and integrated it into the container (index.js). Now, up ...

Jstree: Whenever I refresh my tree, the checkboxes do not reset to default and remain unchecked

After attempting to implement the following code: $("#jstree_demo_div").jstree("destroy").empty(); Although it successfully removes the checked nodes and reloads the tree, it fails to apply the new changes. Any advice on how to resolve this issue would b ...

Express: Every declaration of 'user' must have the same modifiers

In my application, I am utilizing both express and passport. Within these packages, there is a user attribute within the Request interface. Currently, the express package has a user attribute in the request object, such as req.user, but no additional prope ...