-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Additional generic type constraints #12105
Description
I'm trying to produce method signatures where I can provide an interface as a generic type parameter and have a regular parameter that has a constraint on implementing that interface.
doSomething<U, T implements U>(myParam: T): void {
...
}
interface IDemo {
look(): void;
}
class Demo implements IDemo {
look(): void {
...
}
}
thisShouldWork(): void {
doSomething<IDemo>(Demo); // this is the type - not an instance
}As far as I know this is currently not possible in TypeScript.
The two things I'm missing are:
- a generic type constraint
implementsthat enables a better use of interfaces - a type check that does not depend on an instance, but works with the pure type
With the current implementation of TypeScript I cannot use a type as an actual value to a constrained parameter - I have to create a instance of it for the type check to work
doSomething<U>(myParam: U): void {
...
}
interface IDemo {
look(): void;
}
class Demo implements IDemo {
look(): void {
...
}
}
thisShouldWork(): void {
const instance = new Demo();
doSomething<IDemo>(Demo); // error
doSomething<IDemo>(instance); // works
}I have a strong C# background so I might be a bit spoiled of the generic type constraints there, but the C# implementation enabled me to do everything that I imagined possible with generics.
If there are no technical obstacles that make these features hard or even impossible to implement, I think that could leverage TypeScript to give developers the same power as C# does - especially when building frameworks.
These sure are not all scenarios for additional generic type constraints, but the ones I really have been missing so far.