Exploring TypeScript's focus on type in type checking (part 2)

Can TypeScript ensure that a parameter is of a specific type or its derivatives, rather than just an instance of that type?

TypeScript type checking on type rather than instance

In the first part, the solution involves using the typeof keyword

Example

function giveMeAType(type: typeof Foo): void {
}

or with generics

function giveMeAType<T extends typeof Foo>(type: T): void {
}

Exploring this solution further reveals an issue when constructors are introduced to derived types

class Mangler<T> {
    protected constructor(
        public readonly item: T) {
    }

    public static getManglers(mangler: typeof Mangler): typeof Mangler[] {
        var whatever = [];
        return whatever;
    }
}

class StringMangler extends Mangler<string> {
    // No constructor override here...
}

class NumberMangler extends Mangler<number> {
    // However, in this case, I need one...
    private constructor(
        public readonly item: number) {
        super(item);
    }
}

// This works since StringMangler does not override the constructor.
Mangler.getManglers(StringMangler);

// But it fails when overriding the constructor for NumberMangler
Mangler.getManglers(NumberMangler);

Playground

How can we have Type checking with constructor overrides?

P.S. It is desired for derived types to have options for private or protected constructors!

Update 1

Expanding on Nitzan Tomer's answer, giving the constructor a protected status resolves the error, but polymorphism cannot be achieved...

class NumberMangler extends Mangler<number> {
    // The polymorphic constructor in this example doesn't function as expected.
    public constructor(
        public readonly item: number,
        public readonly name: string) {
        super(item);
    }
}

Answer №1

To eliminate the error, you can set the NumberMangler.constructor as protected:

class NumberMangler extends Mangler<number> {
    protected constructor(
        public readonly item: number) {
        super(item);
    }
}

Update

This revised version should function correctly:

class NumberMangler extends Mangler<number> {
    protected constructor(item: number);
    protected constructor(item: number, name: string);
    protected constructor(
        public readonly item: number,
        public readonly name?: string) {
        super(item);
    }
}

The additional non-implementation signatures may not be necessary, but they do enhance readability.

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

There are currently no TypeScript definitions or documentation available for the Material UI v5 TextField component

Check out the playground link here. Why is it that TypeScript typings on TextField are not functioning properly? import TextField from "@mui/material/TextField"; import Select from "@mui/material/Select"; export default function App() ...

Angular - Tips for effectively positioning a fixed navbar while scrolling to sections sharing the same ID

In my Angular project, I've set up different sections on a page, each with its own unique ID. There's also a fixed-position navbar for easy navigation between these sections. My main objective is to ensure that when a user clicks on a menu item ( ...

Retrieving a list of actions triggered: Redux

In my Angular project, I am utilizing Redux to manage state and handle API calls. While exploring the redux devtools, I discovered a comprehensive list of executed actions. Is there a method to access a similar list of actions triggered within my angular a ...

Implementing Observable in NativeScript with TypeScript - A Step-by-Step Guide

Recently, I delved into the world of native-script framework and decided to dive into the "Get Started with JavaScript" tutorial provided on their official website. My background in Java has made me more comfortable with typescript, so I attempted to swap ...

I'm facing an issue with SSRProvider in my NextJs application

My application is developed using NextJs and Typescript, utilizing the react-bootstrap library for creating components. I am facing an issue where I keep receiving an error message stating that When server rendering, you must wrap your application in an &l ...

Angular 5 - Creating a dynamic function that generates a different dynamic function

One of my latest projects involved creating a versatile function that generates switch-case statements dynamically. export function generateReducer(initialState, reducerName: ReducerName, adapter: EntityAdapter<any>): (state, initialState) => ISt ...

Angular2 - Issue with calling toPromise() method on this.http.get() function, as it is not recognized

I was following a tutorial on angular.io called Tour the Heroes, but instead of sticking to the tutorial I decided to make a real GET request for some JSON data. Here is a snippet of my code: private userUrl = 'https://jsonplaceholder.typicode.com ...

How to toggle element visibility when hovering in Angular?

I've set up an angular material card that includes a close button (marked with an "x"). My goal is to initially hide the "x" button and only display it when hovering over the card. Here is the code snippet for the card: <mat-card> <mat- ...

Issue: Express, Mocha, and Chai Error - Server is not running

I am currently developing a TypeScript Express application that retrieves information about YouTube videos. Below is the router configuration (mounted to /api): import express from 'express'; import ytdl from 'ytdl-core'; import body ...

Tips for storing the device token received from Firebase Cloud Messaging in an Ionic2 application

Using the FCM plugin for ionic2, I was able to successfully implement push notifications. For reference, you can check out the plugin here. I followed the steps outlined in this Github repository, and everything is working smoothly so far. Now, my next go ...

Having issues with unexpected token in Typescript while using "as HTMLElement" type?

I recently started learning Typescript and I encountered an error while using the HTMLElement type in a forEach loop: ERROR in ./app/javascript/mount.jsx Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: /Users/me/projects/m ...

Angular Datatables - Equivalent function for fnInfoCallback

Scenario using Angular Datatables In my previous experience with jQuery, I was able to accomplish the functionality shown in the images below: https://i.sstatic.net/VoT2A.png Each Tab displayed a datatable, with the count of filtered records shown next ...

Is it possible for a redis client to function without having a redis datastore installed?

Currently in my node web server, I am utilizing the npm module known as redis. Upon executing my code... const client = redis.createClient(); client.on("error", function (err) { console.log("Error " + err); }); client.hmset(["key", "test keys 1", "t ...

How to specify in TypeScript that if one key is present, another key must also be present, without redundantly reproducing the entire structure

In my code, I have a custom type defined like this (but it's not working): type MyType = | { foo: string; } | { foo: string; barPre: string; barPost: string; } | { foo: string; quxPre: string; qu ...

Struggling to successfully pass React props.children

Currently, I am utilizing react in my project and I have encountered an error when passing props.children to the Header component. Despite passing React as the type, the following error message is displayed. I am unsure why this error is happening. e ...

"Angular EventEmitter fails to return specified object, resulting in undefined

As I work on a school project, I've encountered a hurdle due to my lack of experience with Angular. My left-nav component includes multiple checkbox selections, and upon a user selecting one, an API call is made to retrieve all values for a specific " ...

Guidance on Sending Slider Values to a React Form within a Component

I am currently developing a React application using Typescript. One of the features I implemented is a multi-step form, where each form page is its own component and fields are individual components as well. While I can successfully view data from Text Fie ...

Have you noticed the issue with Angular's logical OR when using it in the option attribute? It seems that when [(ngModel)] is applied within a select element, the [selected] attribute is unable to change

Within the select element, I have an option set up like this: <option [selected]=" impulse === 10 || isTraining " value="10">10</option> My assumption was that when any value is assigned to impulse and isTraining is set to true, the current o ...

The juvenile entity does not align with the foundational entity [typescript]

After setting "strict": true in my tsconfig.json, I encountered compiler errors when attempting to run the code. To replicate and explore this issue further, you can try running the following code snippet. The problem arises when the child clas ...

What causes the error message saying 'undefined' cannot be assigned to the specified type ...?

I just finished developing an innovative Angular application. Within the app.component.html file, I have included: <bryntum-scheduler #scheduler [resources] = "resources" [events] = "events" [columns] = "schedul ...