microsoft / microsoft/TypeScript
Allow inference of class generics when declaring an interface
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
interface, inference, extending class
Suggestion
I'd like to be able to strongly type an interface such that when it is used on a class that has a generic I can infer the type of that generic to then use in the declaration of the interface.
Use Cases
I want to use this within a library that exposes both an abstract class and an optional interface that developers can opt-in to use. The abstract class has one generic parameter, and in order to correctly type the interface without duplicate generic declaration I want to be able to infer the abstract class' generic type.
Currently the inheriting class declarations must duplicate their generic type declaration.
This issue is similar to https://github.com/microsoft/TypeScript/issues/26242 I think, but I don't see how the resolution of that issue will fix this one.
Examples
abstract class Base<T> {
// implementation omitted for brevity
}
// ⬇️this is the proposed new syntax ⬇️
interface Remap<T> extends Base<infer U> {
remap(input: U): T;
}
class Foo extends Base<string> implements Remap<number> {
public remap(input: string): number {
return input;
}
}
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No source files, tests, or compiler entry points are identified in the issue. Start by reading the proposed TypeScript syntax and the related issue #26242, then trace how generic inheritance and interface declarations are currently checked. Done means the team has defined and implemented the intended inference behavior with coverage for the shown example and its edge cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100