What sets Interface apart from InstanceType<typeof Class> when used as a variable type?

Let's take a look at an example implementation:

HttpService.ts:

export interface IHttpService {
  request(): Promise<any>;
  formPostRequest(): any;
}

export class HttpService implements IHttpService {
  public async request() {
    // Implementation goes here
  }

  public formPostRequest() {
    // Implementation goes here
  }
}

Now, let's see how we can use HttpService with dependency injection. Here's an example:

GoogleAccount.ts:

import { HttpService } from './HttpService';

class GoogleAccount {
  private httpService: InstanceType<typeof HttpService>;
  constructor(httpService: InstanceType<typeof HttpService>) {
    this.httpService = httpService;
  }

  public findGoogleAccountById(id: string) {
    return this.httpService.request();
  }
}

The code above utilizes InstanceType and typeof, which are predefined types in TypeScript.

Another approach I often use is to define the type of httpService using an interface. Here's how it looks:

import { IHttpService } from './HttpService';

class GoogleAccount2 {
  private httpService: IHttpService;
  constructor(httpService: IHttpService) {
    this.httpService = httpService;
  }

  public findGoogleAccountById(id: string) {
    return this.httpService.request();
  }
}

Both methods work seamlessly within the TypeScript type system without any complaints from tsc. However, is using

InstanceType<typeof HttpService>
really necessary for this scenario?

Answer №1

I concur that using

InstanceType<typeof HttpService>
is unnecessary if you already know the interface you are implementing. It's best to reserve InstanceType for situations where accessing the underlying type directly is not possible. For more information on appropriate use cases, check out this helpful link.

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

"Adjusting the position of an Ionic Menu on-the-fly

As I strive to update the Ionic 3 Menu side dynamically when the user changes the language, a challenge arises for RTL languages where the menu needs to be on the right instead of the default left. To tackle this issue, I have subscribed to the TranslateS ...

Subclass method overloading in Typescript

Take a look at this example: class A { method(): void {} } class B extends A { method(a: number, b: string): void {} } An error occurs when trying to implement method() in class B. My goal is to achieve the following functionality: var b: B; b.met ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

Using TypeScript for Routing in Angular

I encountered an error message that says the module 'route' is not available. I'm not sure why this is happening, any thoughts? "Uncaught Error: [$injector:nomod] Module 'route' is not available! You either misspelled the module n ...

Tips for accurately defining prop types in next.js when utilizing typescript?

Here is the content of my index.tsx file: import type { NextPage } from "next"; type AppProps = { articles: { userId: number; id: number; title: string; body: string; }; }; con ...

Managing relationships within TypeORM's single table inheritance using a base class for targeting relations

In my application, I aim to provide users with notifications in the form of news items of various types. The relationship between User and NewsItem needs to be one-to-many, with NewsItem serving as a base class for different types of news items. Below is ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

What is the solution for resolving the no-unsafe-any rule?

Currently incorporating TSLint for maintaining the quality of my Angular TypeScript code. I've opted to activate the 'no-unsafe-any' rule from TSLint, as it appears beneficial to avoid making assumptions about properties with type 'any& ...

What is the method for including as: :json in your code?

I have a file with the extension .ts, which is part of a Ruby on Rails application. The code in this file looks something like this: export const create = async (params: CreateRequest): Promise<XYZ> => { const response = await request<XYZ> ...

Is Angular Template Polymorphism Failing?

So I'm working with a base class that has another class extending it. export class Person { public name: string; public age: number; } export class Teacher extends Person { public yearsTeaching: number; } Now, in my component, I need to ...

What is the reason behind typescript not needing `undefined` with the ?: operator on arrays?

type Artifact = { a:string } const items : Artifact[] = []; // this will result in a syntax error let z?: Artifact; // assigning undefined to a variable of type Artifact is an error const b : Artifact = undefined; // despite expectations, this assi ...

Dynamic class/interface in Typescript (using Angular)

Is there a way to achieve intellisense for an object created with a dynamic class by passing parameters? Here is the code snippet: Main: let ita: any = new DynamicClass('ITA'); let deu: any = new DynamicClass('DEU'); The DynamicClass ...

Arranging Objects by Alphabetical Order in Typescript

I am struggling with sorting a list of objects by a string property. The property values are in the format D1, D2 ... D10 ... DXX, always starting with a D followed by a number. However, when I attempt to sort the array using the following code snippet, it ...

Customizing the appearance of the Material UI MuiClockPicker with unique style

I am wondering how I can override the styles for MuiClockPicker? I discovered that using createTheme to override the styles actually works for me, but I encountered an error from TypeScript: TS2322: Type '{ MuiOutlinedInput: { styleOverrides: { roo ...

Fast screening should enhance the quality of the filter options

Looking to enhance the custom filters for a basic list in react-admin, my current setup includes: const ClientListsFilter = (props: FilterProps): JSX.Element => { return ( <Filter {...props}> <TextInput label="First Name" ...

Ways to extract information from a database using a parameter

I am currently working with angular cli version 8.1.0 and I have a requirement to pass parameters in the URL and retrieve data from a PHP MySQL database. On the PHP side, everything is functioning correctly and the URL looks like this: http://localhost/rep ...

Guide to importing a markdown document into Next.js

Trying to showcase pure markdown on my NextJS Typescript page has been a challenge. I attempted the following: import React, { useState, useEffect } from "react"; import markdown from "./assets/1.md"; const Post1 = () => { return ...

Self-referencing type alias creates a circular reference

What causes the discrepancy between these two examples? type Foo = { x: Foo } and this: type Bar<A> = { x: A } type Foo = Bar<Foo> // ^^^ Type alias 'Foo' circularly references itself Aren't they supposed to have the same o ...

Iterate over Observable data, add to an array, and showcase all outcomes from the array in typescript

Is there a way to iterate through the data I've subscribed to as an Observable, store it in an array, and then display the entire dataset from the array rather than just page by page? Currently, my code only shows data from each individual "page" but ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...