What is the best way to include an additional value while using TypeScript type constraints?

I have a general class structure similar to this one, but I am looking to include an additional value with T.

@Injectable()
export class Repository<T,// customValue //> {
   constructor(){
     let _value = customValue;
   }
}

-implementation-

@Injectable()
export class ProductService {

  constructor(private repo: Repository<Product, //string or number//>) {
  }

I want to achieve something like the above example. How can I pass a string or numeric value along with a generic parameter in TypeScript?

Answer №1

Instead of using literal values, generic types are fulfilled with type arguments (although there is room for some creative experimentation - but it's not necessary in this scenario).

You have the option to define a listType as limited to string, or even specify it as a string literal type. This can be implemented as shown below (appearing like a union type, yet possessing string values as its type components).

class Repository<T> {
  private itemsRef: T[];

  constructor(private db: AngularFireDatabase, listType: 'products' | 'customers') {
    this.itemsRef = db.list(listType);
  }
}

The drawback here lies in the fact that a user could potentially input an incompatible T and listType. To avoid this issue, consider developing a RepositioryFactory.

Alternate Factory Approach

Below is a revised version featuring a factory method, designed to eliminate compatibility errors.

type ListType = 'products' | 'customers';

class Repository<T> {
  private itemsRef: T[];

  protected constructor(private db: AngularFireDatabase, listType: ListType) {
    this.itemsRef = db.list(listType);
  }

  static getInstance(db: AngularFireDatabase, listType: 'products'): Repository<Product>;
  static getInstance(db: AngularFireDatabase, listType: 'customers'): Repository<Customer>;
  static getInstance(db: AngularFireDatabase, listType: ListType) {
    switch (listType) {
      case 'products':
        return new Repository<Product>(db, listType);
      case 'customers':
        return new Repository<Customer>(db, listType);
      default:
        throw new Error(`No Respository<T> for ${listType}`);
    }
  }
}

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

Beginner's Guide: Building your debut JavaScript/TypeScript library on GitHub and npm

I am looking to develop a simple JavaScript/TypeScript library focused on color conversion. Some of the functions and types I aim to export include: export type HEX = string; export type RGB = { r: number; g: number; b: number }; export type RGBA = { r: n ...

What is the importance of moving prop types into a type or interface in React components?

Consider the scenario where I have a functional component: const MyText = ({ value }) => ( <div className="my-fancy-text">{value}</div> ); Now, when utilizing Typescript, I face the need to introduce typing. A straightforward ...

Setting up ESLint and Prettier for Accurate Error Detection in TypeScript and Next.js Development

As I work with TypeScript and Next.js, I decided to implement strict code formatting rules by adding the following configuration to my eslintrc.json file: "rules": { "prettier/prettier": "error" } However, when I ran npm ru ...

Implementing asynchronous data sharing within an Angular 2 service

I seem to be facing a challenge that I can't quite figure out. My goal is to share data asynchronously between components that I receive from a server. Here is an example of what my service code looks like: import {Injectable} from 'angular2/co ...

Tips for establishing secure communication between a shell app and micro application (frontend) using pubsub technology

I have developed a shell application that serves as the main container for handling all API communications. Additionally, I have created several Micro applications that simply send API request signals to the shell application. When it comes to security, m ...

Which TypeScript AsyncGenerator type returns a Promise?

I am currently in the process of assigning a return type to the function displayed below: async function *sleepyNumbers() { // trying to determine TypeScript type let n = 0; while (true) { yield new Promise(resolve => resolve(n++)); ...

Retrieving the Object value in Primeng p-dropdown when there is a change in selection

In my p-dropdown, I am trying to extract the selected value. <p-dropdown optionLabel="name" [options]="things" placeholder="Select Thing" [(ngModel)]="input" (onChange)="getValue(input)"></p-dropdown> typescript: //each lin ...

I am encountering an issue with importing modules from the public folder in Next.js when using TypeScript, as I am

I've been running into an issue with importing files in Next.js using TypeScript. I'm trying to use regular imports with custom absolute paths, but I keep getting a module not found error. Oddly enough, my IDE is able to locate the file when I cl ...

Combining type inference validation and authentication middleware in Express routes can be a powerful way to enhance security and ensure

I am struggling to grasp how types are automatically determined in Express routes when utilizing multiple middlewares. To conduct validation using zod, I have employed the middleware package express-zod-safe, although a similar issue arose with alternativ ...

How can I display a component only after another component has finished loading in ReactJS with Typescript?

I am looking to incorporate external scripts into my ReactJS/TS application, but I want to include them in a separate component rather than directly in index.html. if (root) { createRoot(root).render( <> <Scripts /> <Browse ...

React Fiber Mesh Element employs the useRef hook, causing 'ref.current' to potentially be 'undefined'

Web Development Tools Exploring Next JS, TypeScript, and React Fiber Sample Code import { useFrame } from '@react-three/fiber' import React, { useRef, useState } from 'react' interface PolyhedronCanvasProps { position: [number, ...

The dependency that was installed in the node_modules directory is now showing as missing the

I have encountered an issue with 2 TS packages. The first package, project-1, is installed as a dependency in the second package, project-2. While I am able to import and access all type definitions of project-1 in project-2, the dependencies (node_modules ...

Tips for maintaining knowledge after redirecting to a new page

Building an app using Ionic 4 where I need to display vouchers from a database as images. Each image should act as a link to a details page showing more information about that specific voucher. However, I am struggling to figure out how to keep track of th ...

Setting up types for variables in Angular 2 componentsHere is an

I have a model that consists of multiple properties, and I aim to set all these properties with a default value of either empty or null. Here is an example of my Model: export class MyModel { name: string; jerseyNumber: number; etc... } In m ...

Typescript - Conditional Type and Optional Arguments

My component has various arguments that can be passed to it: interface Props { label: string; children?: React.ReactNode; withoutActions?: boolean; fieldKey?: KeyProperties; corporate: Corporate; } The withoutActions and fieldKey properties are ...

Tips for efficiently calling a function without the need to check if it exists beforehand

I'm looking for a way to access the formik props outside of the form without constantly checking if a function exists before calling it when using refs. Any suggestions on how to achieve this? function BasicInfo({ event, initialValues, onSubmi ...

Typescript check for type with Jest

Assume there is an interface defined as follows: export interface CMSData { id: number; url: string; htmlTag: string; importJSComponent: string; componentData: ComponentAttribute[]; } There is a method that returns an array of this obj ...

Retrieve the current state of the toggle component by extracting its value from the HTML

I have a unique component that consists of a special switch and several other elements: <mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle> <p> ... </p> F ...

Troubles with Type Inference in Typescript Conditional Types

Explore the Unique Playground Given a specific type: export declare type CustomFilter<T> = { [P in keyof T]?: (P extends keyof T ? T[P] : any); }; Encountering an issue when defining the filter as follows: update.$setOnInsert.createdAt = new Date ...

Creating a nested type using template literal syntax

Given a two-level nested type with specific properties: export type SomeNested = { someProp: { someChild: string someOtherChild: string } someOtherProp: { someMoreChildren: string whatever: string else: string } } I am looking ...