Description
Suggestion
I would really like to get type checking of static members up front:
class Vehicle
static implements VehicleTypeStatic
implements VehicleType
extends SomeOtherClass
{
// ...
}
🔍 Search Terms
is:issue static implements label:Suggestion
Possible duplicates:
- Introduce a way to enforce a static contract #1263
- Why doesn't TypeScript provide a way to implement an interface on the static side? #17545
- Enforce definite initialization of
static
members #27899
✅ Viability Checklist
I believe this is safe, as it would be new type-only syntax. Currently, the TypeScript compiler would treat it as a syntax error.
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, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
Add a static implements keyword pairing to specify a class's static members combine to implement a particular interface. It could be the other way around:
class Vehicle
implements VehicleType, static VehicleTypeStatic, static SomeOtherStaticInterface
extends SomeBaseClass
📃 Motivating Example
microsoft/TypeScript-Website#2636
I can directly use the implements
clause to enforce the type contract on instances of a class, but the class syntax gives no direct way to enforce a type contract on the static members of the class. The best we can currently do is to declare a short-lived constant embedded in the class:
interface VehicleType {
manufacturer: string
}
interface VehicleTypeStatic {
readonly wheelCount: number;
}
class Vehicle implements VehicleType
{
static {
const temp: VehicleTypeStatic = Vehicle;
void(temp);
}
readonly manufacturer: string;
constructor(maker: string) {
this.manufacturer = maker;
}
static readonly wheelCount = 4;
}
This leaves behind a little bit of run-time code, though, to enforce the type contract. In particular, this constraint appears in neither the generated .d.ts
or .js
files.
💻 Use Cases
This really has only one: defining the type which a class must implement for its static members.