Automatic type inference for TypeScript getters

It appears that Typescript infers field types based solely on the private variable of a field, rather than taking into account the getter's return type union (1) or inferring from the getter itself (2):

    test('field type inference', () => {
  class A {
    x_: number;

    // 1: No type checking for the getter
    get x(): number | undefined {
      if (this.x_ === 1) return undefined;
      return this.x_;
    }

    set x(v: number | undefined ) {
      this.x_ = +v;
    }
  }

  const a = new A();
  a.x = 1;

  // 2: Inferred type is number (based on x_, not getter)
  const x: number = a.x;

  console.log(a.x) // outputs 'undefined'
})

Questioning if this behavior is specified or expected?

Note that even with strictNullCheck, these issues are not caught. It only detects missing initialization and setter errors.

An updated example to fix warnings with strictNullCheck:

test('field type inference', () => {
  class A {
    x_: number;

    get x(): number | undefined {
      if (this.x_ === 1) return undefined;
      return this.x_;
    }

    set x(v: number | undefined ) {
      this.x_ = +(v ?? 0);
    }

    constructor(value: number) {
      this.x_ = value;
    }
  }

  const a = new A(2);
  a.x = 1;

  const x: number = a.x;

  console.log(a.x)
});

Answer №1

Initially, when working with properties in TypeScript, the assumption is that reading from a property will retrieve the most recently written value for that property. However, your getter/setter setup breaks this convention. Despite this, TypeScript does not detect any issues because each get/set function is technically type-safe on its own.

Additionally, when you assign a constant to a property typed as a union, TypeScript remembers which member of the union applies for the remainder of that scope. The logic within the getters/setters does not affect this behavior.

This behavior is related to the public property, not the private one.

For example, consider this simple class:

// No getters/setters
class B {
  x: number | undefined
}

const b = new B()
b.x // number | undefined
b.x = 1
b.x // number

In this case, TypeScript remembers the assigned value, knows it is not undefined, and updates the resulting type of the property where it can determine this to be true.


Now, let's look at this class:

// Useless getters/setters
class C {
  get x(): number | undefined {
    return undefined;
  }

  set x(v: number | undefined ) {
    // no-op
  }
}

const c = new C()
c.x // number | undefined
c.x = 1
c.x // number

Here, the getters/setters are considered useless but still yield unexpected results.

Playground


According to TypeScript, a getter should return the last set value if that value was set in the same synchronously executed scope. Most programmers would likely expect the same behavior.

While ideally the compiler would flag an issue in this scenario, ensuring type safety through these setters is actually quite complex.

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

Creating a unique custom selector with TypeScript that supports both Nodelist and Element types

I am looking to create a custom find selector instead of relying on standard javascript querySelector tags. To achieve this, I have extended the Element type with my own function called addClass(). However, I encountered an issue where querySelectorAll ret ...

How can you eliminate the prop that is injected by a Higher Order Component (HOC) from the interface of the component it produces

In my attempt to create a Higher Order Component, I am working on injecting a function from the current context into a prop in the wrapped component while still maintaining the interfaces of Props. Here is how I wrap it: interface Props extends AsyncReque ...

Please convert the code to async/await format and modify the output structure as specified

const getWorkoutPlan = async (plan) => { let workoutPlan = {}; for (let day in plan) { workoutPlan[day] = await Promise.all( Object.keys(plan[day]).map(async (muscle) => { const query = format("select * from %I where id in (%L) ...

React Native ScrollView ref issue resolved successfully

I'm trying to automatically scroll to the bottom of a flatlist, so here's what I have: const scrollViewRef = useRef(); //my scroll view <ScrollView ref={scrollViewRef} onContentSizeChange={() => { scrollViewRef.current.scr ...

Getting News API and showcasing the information in Vuetify.js card components: A step-by-step guide

I'm trying to develop a news website by utilizing the News API for news data. I obtained an API Key from the official News API website, but my code is encountering some issues. The error message reads: TypeError: response.data.map is not a function ...

Mastering Angular Service Calls in TypeScript: A Comprehensive Guide

In the midst of my TypeScript angular project, I am aiming to revamp it by incorporating services. However, I have encountered an issue where when calling a function within the service, the runtime does not recognize it as the service class but rather the ...

Tips for executing numerous asynchronous tasks in Ionic 3 and closing a loader once all tasks are completed

Currently, I am in the process of developing an Ionic 3 application that offers the feature to cache a list of articles content on demand. The implementation involves utilizing Storage which employs promises for its operations. The code snippet I have wri ...

Using onDoubleClick with MUI TextField: A Quick Guide

Whenever the user double clicks the input field, I would like to automatically select the text. I have created a function for this specific action: export const selectText = ( event: React.MouseEvent<HTMLInputElement | HTMLTextAreaElement, MouseEvent& ...

Exploring the capabilities of Typescript arrays by implementing a forEach loop in conjunction with the

I possess an array: set Array ( [0] => Array ( [name0] => J [name1] => L [name2] => C ) [1] => Array ( [data0] => 3,1,3 [data1] => 5,3 ...

Incorporate MUX Player (Video) into Angular versions 14 or 15

Mux offers a video API service with its own player: MUX Player I am interested in integrating this npm package specifically into a component in Angular 14/15. The JavaScript should only be loaded when this particular component is rendered. Integration Th ...

What steps need to be taken in VSCode to import React using IntelliSense?

When I press Enter in that image, nothing seems to occur. I believed IntelliSense would automatically insert import React from 'react'; at the beginning of the file. https://i.stack.imgur.com/7HxAf.png ...

Utilize the class or interface method's data type

In the context of a child component calling a callback provided by its parent, this situation is commonly seen in AngularJS. As I am utilizing TypeScript, I aim to implement strong typing for the callback in the child component. Here is the initial stat ...

What is the best approach in Typescript to ensure type understanding when importing using require()?

Currently, I am working with TypeScript within IntelliJ. Let's say I have the following code: const functions = require('firebase-functions'); Then I proceed to use it in this manner: exports.doSomething = functions.https.onCall((data, c ...

What is the process for applying cdkDropList to the tbody when using mat-table instead of a traditional HTML table?

I have been experimenting with the mat-table component in my Angular project, following a simple example from the documentation: <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <!--- These columns can be ...

Is it feasible to use a component in a recursively manner?

Following a two-hour search for a solution, I decided to reach out to experts as I suspected the answer might be simpler than expected. The project in question is an Angular7 one. In my goals component, I aim to include a "goal" with a button labeled "+". ...

Ways to verify the identity of a user using an external authentication service

One of my microservices deals with user login and registration. Upon making a request to localhost:8080 with the body { "username": "test", "password":"test"}, I receive an authentication token like this: { "tok ...

How to target a particular Textfield in React with its unique identifier

I'm working on a component that contains various Textfields and need to access specific IDs. For example, I want to target the textfield with the label 'Elevator amount'. I attempted the following code snippet but am unsure of how to correct ...

Retrieve all items that match the ids in the array from the database

I'm having trouble receiving a list of items that match with my array of ids. Here's a snippet from the Angular component code: this.orderService.getSpecyficOrders(ids) .subscribe(orders => { ... Where ids is an array of [{_id : ID }, ...

Utilize the power of generics with Angular's service providers

Is it possible to make the membervar of class Parent generic instead of type any, while still retaining the ability to switch provider classes without having to update all components that rely on class Parent? For example, if class ChildB implements a diff ...

Error: The type 'boolean | (() => void)' cannot be assigned to type 'MouseEventHandler<HTMLButtonElement> | undefined'

Playing audio in a NextJS app while writing code in TypeScript has been an interesting challenge. The onClick() function performs well in the development environment, triggered by npm run dev. <button onClick ={toggle}> {playing ? "Pause" : ...