Is there a way to extend a class with the properties of an interface in Typescript while keeping those properties uninitialized? My ultimate goal is to minimize code redundancy by centralizing property declarations within an interface rather than duplicating them in every class implementation.
I attempted the following approach, but it resulted in errors:
interface Spec {
id: number;
}
class Model<S> {
[K extends keyof S: string]: S[K];
}
class MyModel extends Model<Spec> {
// id: number -- implicit
}
Instead, I managed to make the following code work, although it did not fully achieve my objective:
interface Spec {
id: number;
}
class Model<S, K extends keyof S> {
[K: string]: S[K];
}
class MyModel extends Model<Spec, keyof Spec> {
// id: number -- implicit
}
The issue arose when I added implements Spec
to MyModel:
class MyModel extends Model<Spec, keyof Spec> implements Spec {
// id: number -- implicit
}
This led to the error message,
Property 'id' is missing in type 'MyModel'
.
Though leaving interface properties uninitialized is not a concern as they can be set from the constructor, managing numerous interfaces remains challenging.
NOTE: As I am using an underlying JS module to populate specific properties, the compiler does not necessarily flag missing declarations.