A way to specify class properties using JSDoc
  • 11-Jun-2023
Lightrun Team
Author Lightrun Team
Share
A way to specify class properties using JSDoc

A way to specify class properties using JSDoc

Lightrun Team
Lightrun Team
11-Jun-2023

Explanation of the problem

The issue at hand revolves around the desire to extend the type of an ES6 class using JSDoc comments in order to convey to TypeScript that additional properties may be added to the object later. The suggestion proposes two potential solutions: firstly, the ability to indicate that a class acts as a container that can hold any possible key, and secondly, the ability to use JSDoc comments to specify the presence of other properties on the class. The use case presented involves a class used as a Data Transfer Object (DTO) with some guaranteed properties and optional properties. The current workaround involves using an Object? type annotation, which is deemed unsightly and verbose, as it includes JavaScript code that serves no purpose other than providing type information.

To address the issue, the suggested approach is to utilize JSDoc comments to annotate class properties. The desired outcome is to have the JSDoc annotation convey that the class can be extended with additional properties. The proposed JSDoc comments indicate the presence of the otherProperty property and its optional nature. An alternative approach is to use a JSDoc typedef to define the DTO object type with the necessary properties, including the optional otherProperty. However, this alternative currently encounters a compilation error due to a “Duplicate identifier” conflict. The ultimate objective is to find a way to communicate to TypeScript, via JSDoc comments, that the class can be extended with any property, enabling the usage of instanceof checks.

The suggestion adheres to several guidelines, including not introducing breaking changes in existing TypeScript or JavaScript code, not altering the runtime behavior of existing JavaScript code, and avoiding the need to emit different JavaScript based on expression types. This proposal primarily concerns the development experience and aims to enhance the type system and static analysis capabilities of TypeScript by leveraging JSDoc comments to provide more precise type information. The desired outcome is to enable developers to express the extensibility of classes and to streamline the code by eliminating unnecessary JavaScript code used solely for type information purposes.

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for A way to specify class properties using JSDoc

The provided answers highlight different use cases and concerns regarding the use of JSDoc comments to annotate class properties in TypeScript. Answer 1 showcases a specific use case involving the need to define JSDoc and TypeScript annotations that work together seamlessly while also considering Istanbul code coverage. The examples demonstrate different approaches, such as using a class constructor or a factory function, and explore the challenges faced when trying to incorporate the instanceof operator for type checking. The drawbacks of the existing workarounds, including verbosity, code duplication, and maintenance issues, are emphasized, suggesting the need for a more streamlined solution.

Answer 2 raises a concern related to the runtime behavior introduced by a specific syntax for defining class properties in JSDoc comments. The code example illustrates a scenario where defining the property with an undefined value in the class constructor can lead to unintended consequences and break the code. The desire for an equivalent solution to declare a property type in TypeScript without affecting the runtime behavior is expressed. It acknowledges that although refactoring the code is possible in some cases, it may involve significant effort, particularly in larger JavaScript projects.

In general, these answers reflect a shared sentiment regarding the limitations and challenges of using JSDoc comments to provide type information in TypeScript. While JSDoc supports annotations like @property, there is a desire for tighter integration and better support for class properties within the TypeScript ecosystem. The aggregated response underscores the need for a more direct and standardized approach to define class properties and their types in JSDoc comments, ensuring compatibility with TypeScript and avoiding potential runtime issues.

 

Other popular problems with Microsoft TypeScript

Problem: Incorrect Use of TypeScript Interfaces

TypeScript interfaces are a powerful tool for enforcing strict type checking in a codebase. However, incorrect use of interfaces can lead to problems with code accuracy and maintainability. For example, if an interface is defined with properties that are not used elsewhere in the code, it can be difficult to track down the source of an error later on.

Solution:

To avoid this problem, it is recommended to make use of strict null checking and optional properties in interfaces. Additionally, be mindful of the properties and methods defined in an interface, and make sure that they are actually used elsewhere in the code. If an interface is no longer needed, it should be removed to prevent confusion and errors.

Problem: TypeScript Compilation Errors

TypeScript is a statically-typed language, which means that all type information is known at compile time. This can lead to compilation errors when code is written that violates TypeScript’s type system. For example, if a variable is declared with a type of string, and an attempt is made to assign a value of type number to it, a compile-time error will occur.

Solution:

To resolve TypeScript compilation errors, it is important to carefully review the code and make sure that all variables are correctly declared with the correct type. In cases where a variable needs to be used with different types, a union type can be used to specify multiple types for the same variable. Additionally, the TypeScript documentation provides detailed information about the type system, and can be a valuable resource for resolving compilation errors.

Problem: Managing TypeScript Dependencies

Managing dependencies in a TypeScript project can be challenging, as different libraries and packages may have different versions and compatibility requirements. This can lead to conflicts and errors when attempting to use multiple libraries that have incompatible dependencies.

Solution:

To resolve dependency management issues in a TypeScript project, it is recommended to make use of a package manager such as npm or yarn. These tools provide automated dependency management, and can help to prevent conflicts and errors when using multiple libraries and packages. Additionally, it is important to keep dependencies up-to-date, as newer versions may resolve compatibility issues and improve the overall stability of the project.

A brief introduction to Microsoft TypeScript

Microsoft TypeScript is a statically-typed, open-source programming language that builds on JavaScript. It is designed to provide optional type safety, improved tooling, and enhanced scalability to JavaScript code. TypeScript offers a language structure that is familiar to JavaScript developers, but with the added benefits of static type checking and enhanced tooling support.

TypeScript is designed to be compatible with existing JavaScript code and integrates seamlessly into many popular development environments and build tools. The language offers features such as class and interface definitions, type inference, and advanced type checking, making it easier for developers to write robust, maintainable code. TypeScript also includes a transpiler that can convert TypeScript code into equivalent JavaScript code, allowing developers to write TypeScript code that can run in any environment that supports JavaScript.

Most popular use cases for Microsoft TypeScript

  1. Large-scale web application development: TypeScript is well-suited for developing large-scale web applications, as it provides developers with the ability to write scalable, maintainable code. With its optional type checking, developers can catch type-related errors at compile time, making it easier to catch bugs and reduce the time spent debugging code. Additionally, TypeScript’s compatibility with existing JavaScript code allows developers to gradually adopt the language in their existing codebases, making it easier to transition to a statically-typed codebase.
class User {
    name: string;
    email: string;

    constructor(name: string, email: string) {
        this.name = name;
        this.email = email;
    }
}

const user = new User("John Doe", "johndoe@example.com");
  1. Improved tooling support: TypeScript integrates well with modern development environments and build tools, making it easier for developers to write, manage, and maintain code. With TypeScript’s enhanced tooling support, developers can benefit from features such as code completion, refactoring, and debugging, which can help to increase developer productivity and reduce the time spent on manual code management tasks.
  2. Interoperability with JavaScript libraries: TypeScript is designed to be compatible with existing JavaScript code, making it easy for developers to integrate TypeScript with existing JavaScript libraries and codebases. Additionally, TypeScript provides a way to define type information for JavaScript libraries, making it easier to write TypeScript code that interacts with existing JavaScript libraries in a type-safe manner. This can help to reduce the time spent debugging and improve the overall stability of code.
Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.