You can currently do it much better this way (TypeScript 3.9):

// tslint:disable-next-line: no-any
type Constructor<T> = new (...args: any[]) => T;

export function ofType<TElements, TFilter extends TElements>(
    array: TElements[], 
    filterType: Constructor<TFilter>
): TFilter[] {
    return <TFilter[]>array.filter(e => e instanceof filterType);
}

Example usage:

class ClassA { }
class ClassB { }

const list: ClassA[] = [new ClassA(), new ClassB()];
const filteredList = ofType(list,  ClassB);
Answer from Stephen Weatherford on Stack Overflow
Top answer
1 of 4
20

You can currently do it much better this way (TypeScript 3.9):

// tslint:disable-next-line: no-any
type Constructor<T> = new (...args: any[]) => T;

export function ofType<TElements, TFilter extends TElements>(
    array: TElements[], 
    filterType: Constructor<TFilter>
): TFilter[] {
    return <TFilter[]>array.filter(e => e instanceof filterType);
}

Example usage:

class ClassA { }
class ClassB { }

const list: ClassA[] = [new ClassA(), new ClassB()];
const filteredList = ofType(list,  ClassB);
2 of 4
2

As Judah pointed out it is unlikely to be possible using generic types alone. I found a workaround where I send in one more parameter with the type...

function OfType<T, U>(list: T[], arg: Function) : U[]
{
    var result: U[] = [];

    list.forEach(e => {
        // extract the name of the class
        // used to match primitive types
        var typeName = /function\s*([^(]*)/i.exec(arg+"")[1].toLocaleLowerCase();

        var isOfType = typeof(e) === typeName;

        // if it is not primitive or didn't match the type
        // try to check if it is an instanceof
        if (!isOfType)
        {
            try {
                isOfType = (e instanceof arg)
            }
            catch (ex) { }
        }

        if (isOfType)
            result.push(<U><any>e);
    });

    return <any[]>result;
}

Usage:

var numbers = OfType<any, number>(list, Number);
var foos = OfType<any, Foo>(list, Foo);

alert("Numbers: " + numbers);
alert("Foos: " + foos);

Little redundancy, if someone know a way to remove this redundancy please leave a comment or edit this code.

Or, for primitive types only I could use filter as Judah mentioned.

🌐
GitHub
github.com › microsoft › TypeScript › issues › 5236
generic instanceof · Issue #5236 · microsoft/TypeScript
October 13, 2015 - Automatically insert generic when using instanceof: private static success (check: T | boolean) : boolean { return typeof check === 'boolean' ? check : check instanceof T; } this ...
Author   ken-blocklevel
Discussions

instanceOf parametrization
instanceof only works for classes, but as you mentioned in your comment you can use typeof. That will however only work for primitive types. If you need to check if an object is of a certain type then you need to create your own type guard https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards More on reddit.com
🌐 r/typescript
6
7
June 28, 2022
Generic types not narrowed with instanceof guard
There was an error while loading. Please reload this page · TypeScript Version: 2.0.3 More on github.com
🌐 github.com
7
November 7, 2016
typescript - Infer class generics when using `instanceof` - Stack Overflow
It is not safe to assume that f is of type Foo by checking f instanceof F. The instanceof operator does not care about generics as they are erased at runtime. More on stackoverflow.com
🌐 stackoverflow.com
Create instance of generic type T

You can't do new T() because generics only exist in TypeScript, and there is no way to translate this to Javascript. However, you can do something similar with minor modifications.

    abstract class BaseModel {
        constructor() {
            console.log('BaseModel constructor');
        }

        public abstract doSomething(x: string): string;
    }

    class AModel extends BaseModel {
        constructor() {
            console.log('constructor A');
            super();
        }

        public doSomething(x: string) {
            return `doSomething A: ${x}`;
        }
    }

    class BModel extends BaseModel {
        constructor() {
            console.log('constructor B');

            super();
        }

        public doSomething() {
            return 'doSomething B';
        }
    }

    class Operator<T extends BaseModel> {
        constructor(private readonly _createClass: {new (): T}) {}

        receiveX(): string {
            return 'x received';
        }

        createSomething(): T {
            const x = this.receiveX();
            // Code that's obviously not working:
            const model = new this._createClass();

            model.doSomething(x);
            
            return model;
        }
    }

    const aOperator = new Operator(AModel);
    const aModel = aOperator.createSomething();

    const bOperator = new Operator(BModel);
    const bModel = bOperator.createSomething();

Edits: trying to get code to format.

Edit2: here is a quick stackblitz

More on reddit.com
🌐 r/typescript
4
13
September 29, 2021
🌐
GitHub
github.com › microsoft › TypeScript › issues › 48438
Make `instanceof` operator infer default generic types · Issue #48438 · microsoft/TypeScript
March 26, 2022 - The instanceof operator used for generics, should narrow the template type to its default. class Id { value = 0; } class Box<T extends Id = Id> { constructor(public id: T) {} } function getId(obj: unknown): number { if (obj instanceof Box) { ...
Author   mkol
🌐
DEV Community
dev.to › krumpet › generic-type-guard-in-typescript-258l
Generic type guard in Typescript - DEV Community
April 7, 2019 - But what is this typeGuard<T>? Well, I already wrote a type guard for some TypeA in the example above, so a generic type guard could simply wrap a call to instanceof. We will see a less trivial implementation later.
🌐
Reddit
reddit.com › r/typescript › instanceof parametrization
r/typescript on Reddit: instanceOf parametrization
June 28, 2022 -

Hi,

I am puzzled on how to implement the pseudocode below.

function search(array:Array<any>, type:Function) {

for(let obj of array) {

if(obj instanceof type)

return obj

}

return null

}

search([123, "333", true], String) => should return "333"

Anyone knows how to parametrize the right side of instanceof?

is it even possible in typescript?

Thank you

🌐
Learn TypeScript
learntypescript.dev › 07 › l4-instanceof-type-guard
Using an `instanceof` type guard | Learn TypeScript
instanceof is a JavaScript operator that can check whether an object belongs to a particular class. It also takes inheritance into account. ... The expression returns true or false depending on whether the object belongs to the class or not.
🌐
TypeScript
typescriptlang.org › docs › handbook › 2 › generics.html
TypeScript: Documentation - Generics
Remember, TypeScript can automatically infer variance from your generic types. It’s almost never necessary to write a variance annotation, and you should only do so when you’ve identified a specific need. Variance annotations do not change the structural behavior of a type, and depending on the situation, you might see a structural comparison made when you expected an instantiation-based comparison.
🌐
Judehunter
judehunter.dev › blog › the-caveats-and-solutions-to-generic-type-guards-in-typescript
The caveats of generic type guards in TypeScript · Jude Hunter
September 8, 2020 - if (secretVehicle instanceof Car) { console.log(` This is a car with ${secretVehicle.drive} drive `); // TypeScript doesn't complain, // but this will never print! } What we can do instead, is check if our secretVehicle has all the properties of our subclasses.
Find elsewhere
🌐
GitHub
github.com › microsoft › TypeScript › issues › 12085
Generic types not narrowed with instanceof guard · Issue #12085 · microsoft/TypeScript
November 7, 2016 - class Left<T> { // private foo?: void; constructor(public readonly value: T) {}; } class Right<T> { constructor(public readonly value: T) {}; } function eitherNumberOrString(): Left<number> | Right<string> { return new Left(0); } // e is Left<number> | Right<string> const e = eitherNumberOrString(); if (e instanceof Left) { // e is Left<number> | Right<string>, not narrowed to Left<number> // e.value is number | string, not narrowed to number e.value; }
Author   crobi
Top answer
1 of 3
1

As @TobiasS. and @MuratKaragöz pointed out, the instanceof operator can not distinguish Foo and F at runtime, hence the generics are not passed down.

There are two paths to fixing this:

Using instanceof only

Unsafe at runtime

Instead of typing F with typeof Foo<number> as I did. We can create a new constructor type which return an instance of Foo<number>:

class Foo<T = number> {
  foo: T;

  constructor(foo: T) {
    this.foo = foo;
  }
}

const F: new (...args: ConstructorParameters<typeof Foo<number>>) => Foo<number> = Foo

let f: unknown = new F(0)

if (f instanceof F) {
  f.foo; // number
}

This is a very simple way of typing F, but it IS unsafe at runtime because it tricks Typescript into thinking Foo and F are not the same class, even thought (new Foo()) instanceof F returns true at runtime (see the safer method below).

Although, this trick can still be useful in few niche cases (I personally ended up using a combination of the safe and unsafe methods).

Safe at runtime

This is most likely the preferred solution, as it does not suffer from the same caveat as the unsafe solution above.

Put simply, we can create a new class F which extends Foo<number>:

class Foo<T = number> {
  foo: T;

  constructor(foo: T) {
    this.foo = foo;
  }
}

class F extends Foo<number> {
  constructor(...args: ConstructorParameters<typeof Foo<number>>) {
    super(...args)
  }
}

let f: unknown;

if (f instanceof F) {
  f.foo; // number
}

This IS safer because (new Foo()) instanceof F will return false at runtime, on the opposite of the unsafe solution.

Using type guards

See @TobiasS.'s and @MuratKaragöz's answers.

  • https://stackoverflow.com/a/74626164/8990411
  • https://stackoverflow.com/a/74626118/8990411
2 of 3
1

You could use typeguards e.g

function isF(isF: unknown): isF is Foo<number>{
  return isF instanceof F;
}

if (isF(f)) {
  f.foo; // Foo<number>
}
🌐
Reddit
reddit.com › r/typescript › create instance of generic type t
r/typescript on Reddit: Create instance of generic type T
September 29, 2021 -

I'm having a class hierarchy similar to the following example. First I have some classes that all inherit from one base class. The have doSomething methods that perform some class-specific task that changes properties of the specific instance.

abstract class BaseModel {
    ...
    public abstract doSomething();
}

class AModel extends BaseModel {
    ...
    public doSomething(x) {
        // change AModel instance based on x
    }
}

class BModel extends BaseModel {
    ...
    public doSomething(x) {
        // change BModel instance based on x
    }
}

Then I have some generic class that should be able to operate on all child classes. It receives some value "x" from a database that should be used to call the class-specific doSomething method. Then the instance of the specific class should be returned:

abstract class Operator<T extends BaseClass> {
    ...
    createSomething(): T {
        const x = this.receiveX();
        // Code that's obviously not working:
        const model = new T();
        model.doSomething(x);
        return model;
    }
}

The call should then work as follows:

const operator = new Operator<AModel>();
const aModel = operator.createSomething();

Now I have found out that instantiating an object using new T() is not possible in Typescript. I'm wondering if there is a workaround though. I'd really like to keep the generic aspect of the Operator class. Does anyone have an idea on how to do this?

Top answer
1 of 3
2

You can't do new T() because generics only exist in TypeScript, and there is no way to translate this to Javascript. However, you can do something similar with minor modifications.

abstract class BaseModel {
        constructor() {
            console.log('BaseModel constructor');
        }

        public abstract doSomething(x: string): string;
    }

    class AModel extends BaseModel {
        constructor() {
            console.log('constructor A');
            super();
        }

        public doSomething(x: string) {
            return `doSomething A: ${x}`;
        }
    }

    class BModel extends BaseModel {
        constructor() {
            console.log('constructor B');

            super();
        }

        public doSomething() {
            return 'doSomething B';
        }
    }

    class Operator<T extends BaseModel> {
        constructor(private readonly _createClass: {new (): T}) {}

        receiveX(): string {
            return 'x received';
        }

        createSomething(): T {
            const x = this.receiveX();
            // Code that's obviously not working:
            const model = new this._createClass();

            model.doSomething(x);
            
            return model;
        }
    }

    const aOperator = new Operator(AModel);
    const aModel = aOperator.createSomething();

    const bOperator = new Operator(BModel);
    const bModel = bOperator.createSomething();

Edits: trying to get code to format.

Edit2: here is a quick stackblitz

2 of 3
1

"When creating factories in TypeScript using generics, it is necessary to refer to class types by their constructor functions. "

https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics

see also:

https://www.typescriptlang.org/docs/handbook/2/classes.html#abstract-construct-signatures

🌐
Rico Suter's blog
blog.rsuter.com › how-to-instantiate-a-generic-type-in-typescript
How to instantiate a generic type in TypeScript - Rico Suter's blog.
But how would you write such a method in TypeScript? The main problem is, that the generic type argument T is not available at runtime because TypeScript generics are only used at compile time for type checking and removed in the transpiled JavaScript code.
🌐
GeeksforGeeks
geeksforgeeks.org › typescript-instanceof-narrowing-type
TypeScript instanceof narrowing Type - GeeksforGeeks
April 28, 2025 - Inside the function, we use instanceof to check whether the animal is an instance of Dog or Cat.If it's a Dog, the type of animal is narrowed to Dog, and we can call speak on it to bark.If it's a Cat, the type of animal is narrowed to Cat, and we can call speak on it to meow.Otherwise, if it's not a Dog or Cat, it remains of type Animal, and we call the generic speak method.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-instanceof-generic-type
Understanding TypeScript 'instanceof' with Generic Types
In TypeScript, the instanceof operator is used to check whether an object is an instance of a specific class or constructor function. This operator returns true if the object is an instance of the specified type, and false otherwise. When combined with generic types, instanceof becomes even ...
🌐
Webdevtutor
webdevtutor.net › blog › typescript-instanceof-generic-interface
Understanding TypeScript 'instanceof' with Generic Interface
In TypeScript, the instanceof operator is commonly used to check the type of an object at runtime. When working with generic interfaces, it's important to understand how instanceof behaves and how it can be leveraged to enhance type checking and code readability.
🌐
Kanamesasaki
kanamesasaki.github.io › blog › 20220414-instanceof
TypeScriptのジェネリクスでinstanceof Tしたい | Blog
function get<T>(id:number, arr:Array<any>, cls: new (...args: any) => T) : T { const m = arr[id] if (m instanceof cls){ return m } else { throw Error('unexpected type') } }
🌐
Reddit
reddit.com › r/typescript › if typescript is duck-typed, how come when you use "instanceof", typescript accurately separate out the individual classes that implement the same interface? and how can we take advantage of this functionality in our typing?
r/typescript on Reddit: If typescript is duck-typed, how come when you use "instanceof", typescript accurately separate out the individual classes that implement the same interface? And how can we take advantage of this functionality in our typing?
October 23, 2024 -

Edit: I know that instanceof checks at runtime, I'm very familiar with it and have been using it for many years. My question is specifically how the typing system works in typescript, how/why typescript is able to discern via type inference the difference between Error and PseudoError. And, given that it can, whether it is possible to leverage that kind of discernment to create a utility function that's based on this rather than based on shapes and interfaces.

In lib.es5.d.ts in typescript we have:

interface Error {
    name: string;
    message: string;
    stack?: string;
}

Now in my typescript file, if I create a new type, like this:

class PseudoError {
    name = "hello"
    message = "world"
    stack? = "friends"
}

And I do the following:

const test : PseudoError | Error = new PseudoError()

type withoutError = Exclude<typeof test, Error> // <--- results to never, because of duck typing ?

The above is expected, because PseudoError and Error implement the same interface. So if I'm excluding Error, then I'm also excluding PseudoError by duck type standards.

But when I do this:

if (test instanceof Error) {
  test // <--- hover over = Error
} else {
  test // <--- hover over = PseudoError
}

It suggests that there is obviously some built-in functionality in typescript that doesn't work like in a duck-type-y way. This clearly aligns with the desired outcome in JS, but in my situation, I would like to have an Exclude<...> utility type that does the same thing as what typescript is doing behind the scenes with instanceof.

For example, where's this NotInstanceOf utility function?

const test : PseudoError | Error = new PseudoError()

type withoutError = NotInstanceOf<typeof test, Error> // <--- results to PsuedoError
🌐
Ultimate Courses
ultimatecourses.com › blog › understanding-typescript-instanceof-type-guard
Understanding TypeScript: instanceof Type Guard - Ultimate Courses
August 10, 2019 - That’s an overview of the instanceof, how it works, the prototype and how we can use them to infer types with our Type Guards. The most complete guide to learning TypeScript ever built.