S
SolidJS12mo ago
Basil

TypeScript type for classes that extend class

This Stack Overflow question is what I'm asking, but none of the answers provide intellisense for the function argument: https://stackoverflow.com/questions/76913841/generic-type-to-specify-a-class-which-extends-another I'd like to be able to do something like:
// These class would be accepted:
class Base { /* Various properties, functions, etc. here */ }
class Something extends Base { /* New properties */ }
class SomethingTwo extends Base { /* New properties */ }
class Nested extends SomethingTwo { /* New properties */ }

// This class would not be accepted
class Other { /* New properties */ }

// This is the syntax that is wrong
// vvvvvvvvvvvv
function someFn(arg: extends Base) {
// `arg` would function as if it was just `Base`
}

// Good
someFn(new Base());
someFn(new Something());
someFn(new SomethingTwo());
someFn(new Nested());

// Bad (would be flagged by TypeScript)
someFn(new Other());
// These class would be accepted:
class Base { /* Various properties, functions, etc. here */ }
class Something extends Base { /* New properties */ }
class SomethingTwo extends Base { /* New properties */ }
class Nested extends SomethingTwo { /* New properties */ }

// This class would not be accepted
class Other { /* New properties */ }

// This is the syntax that is wrong
// vvvvvvvvvvvv
function someFn(arg: extends Base) {
// `arg` would function as if it was just `Base`
}

// Good
someFn(new Base());
someFn(new Something());
someFn(new SomethingTwo());
someFn(new Nested());

// Bad (would be flagged by TypeScript)
someFn(new Other());
Stack Overflow
Generic type to specify a class which extends another
In this example I have a Class type which is defined as a class constructor so that I can define methods which accept class constructors as a parameter. I would like that Class also has a generic t...
1 Reply
Brendonovich
Brendonovich12mo ago
// if you don't need generics
function someFn(arg: Base) { ... }

// if you do
function someFn<T extends Base>(arg: T) { ... }
// if you don't need generics
function someFn(arg: Base) { ... }

// if you do
function someFn<T extends Base>(arg: T) { ... }
Want results from more Discord servers?
Add your server