The type of a reference variable in a type definition of another variable

Can we reference the type of one variable (let's call it someVar) in TypeScript when declaring the type of another variable (anotherVar)?

For example, instead of creating a separate type declaration for { complex: 'type' }, can we directly use it as the type for someVar? And then, later in the code, is it possible to conditionally assign the value of someVar to anotherVar or leave it undefined without resorting to using any?

const someVar?: { complex: 'type' } // = ...

// ...

// Desired behavior in pseudocode:
let anotherVar/*: (typeof someVar) */ = undefined

if (condition) {
  anotherVar = someVar
}


Update: TypeScript does have a typeof operator that can achieve this (the above pseudocode is valid TypeScript code), but there are limitations, especially when working with this.

Here's a slightly different scenario:

class Test {
  private someVar?: { complex: 'type' } // = ...

  private someMethod() {
    let anotherVar: typeof this.someVar = undefined // Error: Cannot find name 'this'.

    if (condition) {
      anotherVar = someVar
    }
  }
}

In the case above, how can we address the issue?

Answer №1

Your current code is functioning correctly:

interface Person {
    name: string;
}

const john: Person = {
    name: 'John',
};

let mary: typeof john;
// Now mary is also defined as type Person

Answer №2

Regrettably, the keyof operator does not function with this. There was a discussion regarding this issue on Github which has since been closed and is unlikely to be implemented. A potential workaround could involve referencing the type of the member from the class directly:

class Test {
  private someVar?: { complex: 'type' } // = ...

  private someMethod() {
    let anotherVar: Test["someVar"] = undefined

    if (condition) {
      anotherVar = someVar
    }
  }
}

Playground


Alternatively, as suggested by @Skovy, you could define a type for someVar and utilize it in both instances. In my opinion, this approach is more recommended unless there are specific reasons not to do so.

type ComplexType = { complex: 'type' } | undefined;

class Test {
  private someVar?: ComplexType;

  private someMethod() {
    let anotherVar: ComplexType = undefined

    if (condition) {
      anotherVar = this.someVar
    }
  }
}

Answer №3

To handle both scenarios, you have the option to create a new `type` or `interface` that can be reused.

type A = undefined | { complex: 'type' }

const someVar: A = { complex: 'type'};

let anotherVar: A = undefined

let condition = true;
if (condition) {
  anotherVar = someVar
}

Another way is to utilize the `typeof` operator as suggested:

let someVar: { complex: 'type' } | undefined;

let anotherVar: typeof someVar = undefined

let condition = true;
if (condition) {
  anotherVar = someVar
}

If dealing with a more complex class example, consider using a `type` or `interface`:

type A = { complex: 'type' } | undefined;

class Test {
  private someVar?: A;

  private someMethod() {
    let anotherVar: A = undefined

    let condition = true;
    if (condition) {
      anotherVar = this.someVar
    }
  }
}

An alternate approach that seemed to work involves:

class Test {
  private someVar?: { complex: 'type' }

  private someMethod() {
    let anotherVar: typeof Test.prototype.someVar = undefined

    let condition = true;
    if (condition) {
      anotherVar = this.someVar
    }
  }
}

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

Best Method for Confirming Deletion in Data Table with Shadow and UI

I have a query regarding the Shadcn/UI - Data Table component. In my case, I am working with a list of users where each row has a delete button in the last column. Upon clicking the delete button, a confirmation dialog pops up. Currently, I am implementi ...

Utilizing an AwsCustomResource in AWS CDK to access JSON values from a parameter store

I found a solution on Stack Overflow to access configurations stored in an AWS parameter. The implementation involves using the code snippet below: export class SSMParameterReader extends AwsCustomResource { constructor(scope: Construct, name: string, pr ...

Testing React components with React Testing Library and Effector (state manager) made easy

I am currently utilizing effector along with React Testing Library (RTL). While going through the RTL documentation, I came across an interesting article regarding the usage of customerRender, where we provide AllTheProviders as a wrapper for the render fu ...

Transferring information from child to parent class in TypeScript

I have a scenario where I have two classes (Model). Can I access properties defined in the child class from the parent class? Parent Class: class Model{ constructor() { //I need the table name here. which is defined in child. } publ ...

Ways to capture targeted requests

Utilizing NestJS and Angular 2, I have noticed that both frameworks have a similar approach when it comes to working with Interceptors. I am currently looking for the best practice to identify specific requests in order to perform additional tasks. When d ...

Using absolute imports to resolve modules in TypeScript and Next.js

When I import functions from files using absolute imports, I keep encountering errors that I have been trying to resolve. The errors manifest in a certain way, as shown here: Despite the errors, the functions are successfully imported and usable. It seems ...

Unable to retrieve headers from extended Express.Request type

Currently, I am attempting to enhance the Request in Express so that it accurately represents the structure of a query. My current approach is as follows: export interface TypedRequestQuery<T> extends Express.Request { query: T; } While this met ...

Error in AngularFire2 typings: The property 'take' is not present in the type 'FirebaseObjectObservable<any>'

Recently, I upgraded my ionic app from beta 11 to rc0, which also involved transitioning from typescript 1.8 to version 2. After following the configuration steps for AngularFire2 on the site Getting Started with Ionic 2 RC0, Firebase 3 + AngularFire 2, I ...

Difficulty establishing a connection between Typescript and Postgres results in a prolonged

I am attempting to establish a connection to a Postgres database using typescript. For the ORM, I have opted for sequelize-typescript. The issue lies in the fact that the script seems to hang at await sequelize.sync();. Below is the content of the sequeliz ...

Building an Angular CLI application with Typescript that handles multiple HTTP calls using polling through a timer

I am working with a Django backend and I need to check the status of multiple Celery Tasks () every 3 seconds. For instance, let's say I have 4 task IDs: 3099023 3493494 4309349 5498458 My goal is to make an http.get<...>(backend) call every ...

The element is not defined in the Document Object Model

There are two global properties defined as: htmlContentElement htmlContentContainer These are set in the ngAfterViewInit() method: ngAfterViewInit() { this.htmlContentElement = document.getElementById("messageContent"); this.htmlContentCont ...

How to Retrieve the Current Item in *ngFor Loop Using TypeScript in Angular 4

In my JSON file, I have an array containing 5 people. Each person in the array has a list of items associated with them. In my HTML code, I am using *ngFor to iterate over the people and display their names. Additionally, I want to display the total sum of ...

Customize the color of a specific day in the MUI DatePicker

Has anyone successfully added events to the MUI DatePicker? Or does anyone know how to change the background color of a selected day, maybe even add a birthday event to the selected day? https://i.stack.imgur.com/or5mhm.png https://i.stack.imgur.com/so6Bu ...

I'm having trouble linking MikroORM migration to Postgresql - the npx command keeps failing. Can anyone offer some guidance on what

I am encountering a situation similar to the one described in this post. I'm following Ben Awad's YouTube tutorial: you can see where I am in the tutorial here. Objective: My goal is to execute npx mikro-orm migration:create in order to generate ...

Show data based on the chosen destination

Recently, I've been working on creating a simple printer manager to monitor the status of all my printers. Although I have successfully displayed all the data, I'm facing an issue while trying to organize it by location. The error message I keep ...

There was a serious issue: The mark-compacts were not working effectively near the heap limit, resulting in allocation failure - the JavaScript heap ran out of memory during the

I recently set up a t2.micro server on AWS and encountered an issue when running our application with the command "sudo npm start". The error message I received was: "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript he ...

Having trouble receiving accurate intellisense suggestions for MongoDB operations

Implementing communication between a node application and MongoDB without using Mongoose led to the installation of typing for both Node and MongoDB. This resulted in the creation of a typings folder with a reference to index.d.ts in the server.ts file. In ...

Is there a way to automatically close the previous accordion when scrolling to a new one on the page?

Currently, I am working with the material-ui accordion component and facing an issue where all accordions are initially opened. As I scroll down the page and reach a new accordion, I want the previous ones to automatically close. The problem arises when tr ...

Is there a way for TS-Node to utilize type definitions from the `vite-env.d.ts` file?

I am utilizing Mocha/Chai with TS-Node to conduct unit tests on a React/TypeScript application developed with Vite. While most tests are running smoothly, I am encountering difficulties with tests that require access to type definitions from vite-env.d.ts ...

Angular's DecimalPipe will truncate any strings that exceed 10 digits

Using the decimal pipe to format numbers in an input field value| number:'0.0-6': 'en-us' When working with numbers containing more than 10 digits, it displays as follows: For 11111111111.123456, it formats to 11,111,111,111.123455 ...