Is it possible to mandate that a function parameter must be a constructor of a specific type parameter?

Can we construct the following function signature:

foo<T>(bar: ConstructorOf<T>): T

in a way that allows this code snippet to be valid:

class Baz {}

foo(Baz); // type parameter T inferred as Baz

?

Answer №1

Are you searching for something like this?

class Baz {
  isBaz = true;
}

function foo<T>(c : {new(): T;}): T {
  return new c;
}

console.log(foo(Baz).isBaz); // works fine
console.log(foo(String).length); // works fine
// console.log(foo(String).isBaz); // error: property isBaz does not exist in type String

This snippet is a simplified illustration from the final topic discussed in https://www.typescriptlang.org/docs/handbook/generics.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

Ensure that the array is completely populated before calling it in Angular

My code starts with an empty array and I need to call a service that works with the populated array. Two service calls are used to populate the array, both fetching elements from an API. The issue is ensuring the last service call waits for the array to be ...

Can you explain how the "reduce" function can be implemented using an interface in TypeScript?

Can you explain the "reduce" function using an interface in TypeScript? https://i.stack.imgur.com/X1VxL.png ...

Top tips for accessing and modifying an immutable object within a component retrieved from an RXJS/NGRX store in Angular

This week we successfully updated our Angular v9 app to v11 and RXJS v6.6 with minimal issues. However, due to the store being in freeze mode, we are encountering errors when trying to update the store in certain areas of our code. While most of the issue ...

Tips for submitting a form using a button located outside of a form tag dynamically

I've created a multi-step form with a "next" button to navigate through different steps. On the final page, it transitions to a "submit" button that connects to a form. For this transition, I dynamically set the type and form attributes on the button ...

Issue with selecting an individual value in NGRX entity using id

My goal is to retrieve an object by its Id from the entity state using a reducer. Here is the implementation: export interface MessageState extends EntityState<Message> { // additional entities state properties loaded: boolean; loading: boole ...

Circular Dependencies in Angular (only the file name)

Previously, I used to keep interfaces and services in separate files but later combined them into one file since they were always requested together. For example, instead of having user.interface.ts and user.service.ts as separate files, I now have all the ...

What is the reason for the regeneration of the 2D array?

I have a method called generateWeights() that retrieves random values in an array; And a method named learn() that calls the changeWeights() method to alter the values in the array. Expected: Prior to invoking the learn() method, I anticipate receiving an ...

Encountered an issue with Vue 3 defineProps(): [plugin:vite:vue] Transformation unsuccessful

Currently, I am utilizing Vue version 3.2 along with TypeScript. Whenever I try to declare my props in the following manner: <!-- AppButton.vue --> <script lang="ts"> interface Iprops { buttonType?: string; size?: strin ...

Three.js failing to display objects

I am currently developing a project using modular Three.js with TypeScript. Although the scene is being created successfully, I am facing an issue where no elements are being rendered on the canvas. Below is the snippet of my code: import * as THREE fro ...

Library for manipulating SVG elements using Typescript

After experimenting with Raphael and Snap in my Angular 4 app, I've found that neither of them fully support TypeScript. Does anyone happen to know of a library that offers complete TypeScript type support for easy integration with Angular 2/4/5 witho ...

Develop an interactive React sidebar with changing elements

I'm in the process of developing a sidebar for a project, with the goal of making it similar to tools like Confluence. This means that we need the ability to rearrange documents and create subdirectory structures by simply moving the documents, with ...

Optimizing image imports through treeshaking while integrating Typescript

One of my components has a structure similar to this: import foo from "./assets/foo.svg"; import bar from "./assets/bar.svg"; const icons = {foo, bar}; type IconTypes = "foo" | "bar"; type IconProps = { ic ...

Error message: "Error encountered while building Next.js - ReferenceError: 'describe' is not defined"

I am facing difficulties achieving a successful next build without encountering the following error: > Build error occurred { ReferenceError: describe is not defined Although the dev server and tests execute smoothly, it appears that the jest global d ...

What is the alternative method for applying a CSS class in the click event in Angular 7 without relying on ng-Class or ng-Style?

Is there a way to dynamically add or remove CSS classes to HTML elements in Angular7 without relying on Ng-Style and Ng-Class directives? I'd like to achieve this functionality when clicking on the elements. Appreciate any insights you can provide. T ...

Arranging data in a table by date with "."

My current use case involves working with a table that contains dates and empty strings. Despite expecting the sorting to behave a certain way, I've encountered an issue. Normally, when sorting with strings, the empty string would typically be placed ...

Creating a dynamic union type in Typescript based on the same interface properties

Is it possible to create a union type from siblings of the same interface? For example: interface Foo { values: string[]; defaultValue: string; } function fooo({values, defaultValue}: Foo) {} fooo({values: ['a', 'b'], defaultVal ...

Obtain the ViewContainerRef object from the Component

Looking to create nested components in Angular 4? This is the Chooser Component import {InputComponent} from './input/input.component' import {BlockComponent} from './block/block.component' export const FormChooser = { Block: Block ...

React Redux Bundle with Hot Reload Feature

Working on a project written in TypeScript with the React and Redux framework, I'm familiar with webpack and its middleware libraries for hot reloading. My question arises when considering how my TypeScript code is first converted to JSX through gulp ...

Tips for refining TypeScript discriminated unions by using discriminators that are only partially known?

Currently in the process of developing a React hook to abstract state for different features sharing common function arguments, while also having specific feature-related arguments that should be required or disallowed based on the enabled features. The ho ...

Ways to eliminate the white background gap between pages on ionic

While developing an app using Ionic, I encountered a strange issue. Everything runs smoothly on a browser, but when testing the app on an Android 5 device, I noticed a white background appearing between pages. The app loads correctly with the custom splas ...