Comparing type inference with explicit type declaration in TypeScript

In my coding experience, I've noticed that some developers declare variables with an explicit type even when the inferred type is clear:

For example: loading: boolean = false, name: string = "John", or count: number = 0, and so on.

I have observed that TSLint prefers the inferred type over the explicit type. This has raised a question in my mind - is this purely a matter of style? Do these explicitly defined types hold any significance during runtime?

Answer â„–1

Many developers in the javascript community today lean towards type inference, citing readability as a key factor. However, readability is not just about fewer letters. Consider the difference between:

I hp I mk m slf clr vs I hope I make myself clear

It's important to be open-minded and explore both approaches before forming a solid opinion. Stay flexible and don't let your views hinder progress.

Keep in mind that

opinion is what I have when I haven't done enough research

If you fully understand the implications of different choices, you won't need an opinion - you'll simply choose the best option. This approach lets logic guide your code, rather than personal preference. It's wise to support decisions made by your team in most cases.

Waiting for runtime errors to surface is a risky strategy, as it can lead to unnecessary downtime and costly bug-fixing processes. Taking the time to identify errors early on can save resources in the long run. Precise types play a key role in this process.

This is why explicit types are my preference. Types should not be hidden - they serve as a formal proof of correctness in your program. Embrace your type system and it will benefit you in return. Remember to annotate variables with their types, even when it may seem unnecessary.

There have been instances where lack of proper typing has resulted in significant losses for companies and projects. Having type information visible can prevent costly mistakes, even if your compiler isn't strict enough to catch them initially.

If your types become overly complex, it's a sign that adjustments are needed. Don't underestimate the importance of precise typing in your codebase.

But remember, everyone makes mistakes - including me...

Answer â„–2

When looking at your example, it's all about style rather than impacting your code from a compilation perspective. It's important to note that this is specifically for cases where the variable value explicitly defines its type, which could potentially make your code harder to understand when reassigning values from other variables.

In simpler terms, it may be more advantageous to do:

name: string = "John"
bday: Date = "1980/01/10" //the compiler will flag an error

And steer clear of:

name = "John"
bday = "1980/01/10" //no compile error, but it should be new Date("1980/01/10")

Remember: Undefined types will always default to any.

Answer â„–3

At runtime, declared types have no significance. Once the JavaScript code is created, all type information is eliminated because JavaScript does not allow for specifying variable types.

Regarding TSLint's preference for type inference over explicit typing, it likely aims to maintain a DRY (don't repeat yourself) approach. Allowing the compiler to handle typing eliminates the need to clutter the code with unnecessary type declarations.

Answer â„–4

Exploring whether to annotate code or rely on TypeScript's type inference has been a topic of much discussion.

An important consideration is whether the expression or variable being annotated serves as a "boundary" within your codebase, such as exported functions or classes. In these cases, explicit annotations can enhance clarity and understanding for users consuming your APIs.

On the other hand, internal functions and variables specific to a module may not require explicit annotation.

A contrasting perspective from When to add types and when to infer in TypeScript suggests adding types to all function declarations while omitting explicit types for variables.

Furthermore, a viewpoint shared in this article emphasizes incorporating type annotations for function/method signatures but not necessarily for local variables created within their bodies to streamline code readability and maintain focus on implementation logic.

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

Display a loading spinner while refreshing a list

Currently, I am in the process of developing an app using React Native. My goal is to display information (text) below my CalendarList based on data stored in an array. One of the properties in the array is the date. To achieve this, I have created a filte ...

Removing sourceMappingURL from an Angular Universal build: A step-by-step guide

Using this repository as my foundation, I have successfully resolved most of the plugin errors except for one that continues to elude me. It's puzzling because no other plugin anticipates a .map file in an SSR build since it is intended for productio ...

Dynamic forms in Angular do not currently have validation support for forms with multiple parts

I am currently working on creating a dynamic form with multi-part answers using Angular's Dynamic Form example (https://angular.io/guide/dynamic-form) and live example (https://angular.io/generated/live-examples/dynamic-form/eplnkr.html). I have set u ...

Problem with adding card to customer in Stripe using Angular 2 and Express

I encountered an issue while attempting to add a card to a customer. My Express server, which handles the post request to Stripe, successfully registers a new customer but fails to include credit card information for the new customer. Within my Angular 2 ...

Struggling to extract the hours and minutes from a date in IONIC: encountering an error stating that getHours is not a recognized

I encountered an issue while trying to extract the hours and minutes from a date in Ionic. Below is the code snippet from my .html file : <ion-datetime displayFormat="HH:mm" [(ngModel)]='timeEntered1' picker-format="h:mm"></ion-date ...

What causes arrays to unexpectedly change in Angular?

Currently, I am working on a project that involves Angular and Laravel. One interesting issue has arisen in one of my components where I receive a variable from the database as an object array. Surprisingly, even though I only loop through this variable wi ...

Utilizing Angular 2 to Pass an Argument to a Custom Pipe

I've developed a custom pipe that can accept 2 arguments, but I'm unsure of how to pass them. Here's the code for my pipe: export class TranslationPipe implements PipeTransform { private capitalize: boolean; constructor( ...

Determining the argument type in Typescript based on the value of a previous argument

I am struggling to implement type checking on the payload argument of the notify method in the following class. Here is the code I have tried: type UserNotificationTypes = { ASSIGNED_TO_USER: { assignedUserId: string } MAIL_MESSAGE_SENT: { re ...

ng-multiselect dropdown displaying incorrectly upon initial loading

I have incorporated the ng-multiselect dropdown in my Angular application. Issue: Upon loading the program or opening any page with the dropdown, it initially appears like this: https://i.sstatic.net/GRFip.png However, once I click on the div that contai ...

Searching for an active Angular component in Selenium WebDriver - the complete guide!

I am facing an issue with XPath in Selenium webdriver. I can successfully locate an element using XPath in DevTool, but when I try the same XPath in selenium-webdriver, it throws an error saying "no such element: Unable to locate element". I have checked ...

What could be the reason behind [hidden] not functioning correctly following the forkJoin().subscribe() method

Below is the template I am currently using: <div [hidden]="this.days.length > 0" fxLayoutAlign="center center"> <div style="font-size: 1.4em; color: #4e4e4e;"> Empty </div> </div> I am facing an issue where the conditio ...

What is the best way to showcase the selected typeahead value on the input box using ngxTypeahead?

Welcome to the official ngxTypeahead Plunker! Check out the demo here: http://embed.plnkr.co/gV6kMSRlogjBKnh3JHU3/ In this example, I want to display the highlighted (blue) typeahead option's content in the input box when the user presses the keyUp ...

Navigating Universal Rendering with Cookie Implementation in Angular-CLI

In the process of creating an Angular app with angular-cli and implementing universal rendering, I followed the steps provided here. However, it was noted that global variables like window and document cannot be used in the app when using universal rende ...

Enrolling a new plugin into a software repository

I have 5 unique classes: ConfigManager ForestGenerator TreeCreator NodeModifier CustomPlugin My goal is to create an npm module using TypeScript that incorporates these classes. The main feature I want to implement is within the ConfigManager clas ...

Issue with Angular Material 2 Autocomplete: mat-option not firing keyup event

I am currently exploring methods to detect when an mat-option within the mat-autocomplete component is clicked or selected using the enter key. The click event binding functions correctly, but surprisingly the keyup.enter or solely the keyup event does no ...

The p-calendar component is experiencing difficulty updating the time value when using formControlName

Currently, I am experimenting with using p-calendar to record both date and time. While I have been successful in capturing the user-selected date, I am struggling with assigning a default time using formControlName. HTML: <p-calendar id="calenderid" ...

Tips for handling the completion of an asynchronous http subscription within a multi-level nested function

Recently, I've been diving into Rxjs and have been working on setting up a canActivate guard for my nativescript-angular application. The main goal is to check if the user has a JWT token stored, validate it with the server, and redirect them to the h ...

The View is not reflecting changes in the Variable

Is there a way to disable all the buttons when selectedplace is null in the Dialog, as it currently works when the Dialog first starts but remains activated all the time when the option is changed? I have attempted the following: Customized HTML: ...

The ng test is not successful due to a SassError that indicates the stylesheet import cannot be found

I am facing an issue with my .scss files in my Angular project. Everything works fine when I build for development or production, but when I run tests using ng test, I encounter errors like: SassError: SassError: Can't find stylesheet to import. 1 â” ...

Exploring the Powers of Angular's HTTP with rxjs take() Solution

Suppose there is a function within a provider like the one below: getAll(): Observable<CarModel[]> { return this.http.get<CarModel[]>(this.carUrl); } In a component, there is a function that utilizes the aforementioned function from the p ...