Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compile without type declarations showing up as undefined initialisations #58994

Closed
6 tasks done
mksunny1 opened this issue Jun 24, 2024 · 2 comments
Closed
6 tasks done

Comments

@mksunny1
Copy link

πŸ” Search Terms

type declaration

βœ… Viability Checklist

⭐ Suggestion

I would love to see a compiler option for compiling TypeScript files with optional field declarations disappearing from the JavaScript class body. The current behaviour is for the fields to just be listed in the class body which leads to them being initialised to undefined per instance. This can lead to unnecessary memory bloat in some cases. I tried using the exactOptionalPropertyTypes compiler option but unfortunately it does not work for this scenario.

πŸ“ƒ Motivating Example

I am creating a reactive library using TypeScript here. An important detail about my implementation is wrapping existing objects with reactive ones. The wrapping objects have many optional fields, that should not be present at all unless they are needed to function. Typescript enforces type declarations for all members, including optional ones, so that all the properties end up getting initialised to undefined in the output JavaScript.

TS input:

class ReactiveObject {
    children?: { [key: string | number | symbol]?: any }
    props?: any;
    // ...
}

JS output:

class ReactiveObject {
    children;
    props;
    // ...
}

What I prefer:

class ReactiveObject {
    // ...
}

My current workaround is to manually comment out the optional variables after compiling, but this cannot scale in an automation environment.



### πŸ’» Use Cases

1. What do you want to use this for? To create a memory-efficient reactive library.
2. What shortcomings exist with current approaches? Unnecessary memory allocations
3. What workarounds are you using in the meantime? Manually editing the output JavaScript
@MartinJohns
Copy link
Contributor

This is working as intended and is for compatibility with the ECMAScript standard. You can disable the behavior by turning off useDefineForClassFields.

@mksunny1
Copy link
Author

Thanks @MartinJohns. Knew there should be something for this...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants