I had high hopes that TypeScript's automatic type inference for constructor parameters would do the trick, but it seems to have let

You can experiment with the given code snippet at the online playground to confirm it.

Consider this code:

class Alpha {

        private beta;

        constructor(b: Beta) {
                this.beta = b;
        }

        doSomething() {
                this.beta.doesNotExist();
        }

}

class Beta {

}

I was expecting the compiler error

Property 'doesNotExist' does not exist on type 'Beta'.
.

However, you only receive that error if you specify the type for beta like this:

private beta:Beta;

I assumed TypeScript would infer types for parameter assignments. For instance, the parameter b is of type Beta. You can verify this by adding the following in the constructor:

const test:string = beta;

Upon doing so, you will encounter an error message stating

Type 'Beta' is not assignable to type 'string'.
.

Hence, my query is, why isn't private beta automatically assigned the type of beta?

Or is this a lesson I need to learn and consistently specify types for all private constructor members?

Answer №1

Does TypeScript really include type inference for parameter assignments?

Negative.

Solution

In reality, there are two methods:

Add explicit annotation to the member

class Alpha {

        private beta: Beta; // add annotation

        constructor(b: Beta) {
                this.beta = b;
        }

        doSomething() {
                this.beta.doesNotExist();
        }

}

class Beta {

}

Combine the parameter and member declaration (preferred)

class Alpha {
        constructor(private beta: Beta) { // observe `private`
        }

        doSomething() {
                this.beta.doesNotExist();
        }

}

class Beta {

}

Additional Information

Some insights on inference : https://basarat.gitbooks.io/typescript/content/docs/types/type-inference.html

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

Learn how to use sanitizer.bypassSecurityTrustStyle to apply styling to Pseudo Elements before and after in a template

Currently, I am attempting to add style to a pseudo element :after <a class="overflow">{{item?.eco}}</a> My goal is to modify the background color of a:after, and I believe this adjustment needs to be made in HTML. I've been thinking ...

Employing async/await for efficient data retrieval

Attempting to utilize async-await in TypeScript Vue 3 to retrieve data, but encountering an issue where the function is already logging 'undefined' (or executing before the function call) private async exportDataOrder() { await this.getDataEx ...

I attempted to unsubscribe from an observable in Angular, but I encountered an error stating that the unsubscribe function does not exist

Here is the code snippet from a components.ts file in an Angular project. I encountered the following error during compilation: ERROR merge/merge.component.ts:75:12 - error TS2551: Property 'unsubscribe' does not exist on type 'Observable& ...

Issues arise when attempting to override attributes within the HTML of a parent component in Angular

Why does overriding an attribute in a child class that extends from another not work as expected? Here's a made-up scenario to simplify the issue: Parent class file: gridbase.component.ts import { Component, OnInit } from '@angular/core'; ...

Employ the VSTS node API to retrieve all commits within a specified branch

I have been utilizing the vsts-node-api with reasonable success. However, my goal is to retrieve all commits in a specific branch, as detailed in the REST API documentation located here. Unfortunately, the node api only allows for commit queries in a rep ...

Asynchronous handling of lifecycle hooks in TypeScript for Angular and Ionic applications

I'm intrigued by the idea of integrating TypeScript's async/await feature with lifecycle hooks. While this feature is undeniably convenient, I find myself wondering if it's considered acceptable to make lifecycle hooks asynchronous. After ...

The ajv-based middy validator does not adhere to the specified date and time format

When it comes to validation, I rely on middy as my go-to package, which is powered by ajv. Below is an example of how I set up the JSON schema: serviceDate: { type: 'string', format: 'date-time' }, The structure o ...

Filter the angular accordion by passing a simple array value into the input

I am looking to filter my array of accordion items based on the value of the question matching the input I provide. I have tried using the filter method for this. this.accordionItems = [ { "topic":"polizze", " ...

The object is not a valid function

Within this class object, I have an instance of a class that I am unable to call its functions within. Despite the IDE allowing me to call the getPoistionDiagram function: export class NodeW { childrenIds: string[]; diagram?: { coordinates: { ...

String date in the format "dd-MM-yyyy" cannot be transformed into a date using the 'DatePipe' function

Having trouble with date conversion in my custom pipe. It seems that when using a locale of 'nl-nl' and trying to format the date as 'dd-MM-YYYY', I'm seeing an error message stating Unable to convert "16-02-2023" into a ...

Retrieving chosen row data in Angular 6 Material Table

I am attempting to send the value of a selected row from one component to another upon clicking a button. However, in this particular example, I'm unsure where to obtain the selected row values and how to pass them on button click. After that, routing ...

Merging objects with identical keys into a single object within an array using Typescript

Here is the array that I am working with: Arr = [{ code: "code1", id: "14", count: 24}, {code: "code1", id: "14", count: 37}] My objective is to consolidate this into a new array like so: Arr = [{ code: "code1& ...

Managing empty functions as properties of an object in a React, Redux, and Typescript environment

I'm feeling a little uncertain about how to properly test my file when using an object with a function that returns void. Below are the details. type Pros={ studentid: StudentId pageId?: PageID closeForm: () => void } When it comes to creating ...

Application Initialization Error: appInits is not a valid function

When my Angular v17 application starts, I need to set some important values right away. This is how it's done in app.config.ts: export const appConfig: ApplicationConfig = { providers: [ ConfigService, ... { pr ...

The term "Exports" has not been defined

I'm currently facing a challenge trying to develop an Angular application based on my initial app. The process is not as smooth as I had hoped. Here's the current setup: index.html <!DOCTYPE html> <html> <head> <base h ...

Exploring the Module System of TypeScript

I am working with a TypeScript module structured like this: let function test(){ //... } export default test; My goal is for tsc to compile it in the following way: let function test(){ //... } module.exports = test; However, upon compilation, ...

How does a brand new installation of VSCode believe it comes pre-equipped with TypeScript capabilities?

Operating on Windows 10 Enterprise, After investing several hours and experimenting on various VMs, Interesting Observation #1 Upon opening a .ts file in vscode, it appears to be recognized as TypeScript 2.3.4 as per the screenshot provided below: http ...

Number as the Key in Typescript Record<number, string> is allowed

As a newcomer to TypeScript, I am still learning a lot and came across this code snippet that involves the Record utility types, which is quite perplexing for me. The code functions correctly in the playground environment. const data = async (name: string ...

Guide on creating dynamic route paths for includes within a Pug template

Need help creating a dynamic include For example: h1 include path/#{object} or include path/+{object}+{a:true,b:11} Something similar to the above. If anyone knows how to achieve this using Mixins in pug, please provide an example for include. ...

Is there a way to inform TypeScript that an object can only return properties from values found within an array?

I am trying to ensure that the return object from a function in TypeScript only allows keys that correspond to string values present in an array passed as an argument to the function. The returned object should contain a subset of keys from a list of valid ...