ertucode
ertucode

Reputation: 655

How to only allow classes that require a specific type of generic

I am currently using this to check if something is a class.

type Class = { new (...args: any[]): any };

How to make it so that it only accepts classes that require a specific type of generic. For example, if I have these classes.

class A<T>{}
class B<T extends any[]>{}
class C{}

I need a type that only accepts class B.

Upvotes: 0

Views: 412

Answers (1)

f91kdash
f91kdash

Reputation: 338

You can not identify A/B/C in your example. You must have constructor in the class, and the generic must clearly

type Class = { new<T extends string[]>(data: T): any }

class A<T extends string> {
    data: T
    constructor(data: T) {
        this.data = data
    }
}

class B<T extends string[]> {
    data: T
    constructor(data: T) {
        this.data = data
    }
}

class C {
    data: number
    constructor(data: number) {
        this.data = data
    }
}

function test(x: Class) {
    ...
}

test(A) // Error
test(B) // OK
test(C) // Error

Upvotes: 2

Related Questions