My goal is to create a class that inherits all the properties of an interface, without explicitly declaring those properties itself. The interface properties are added during the build process and will be available at runtime.
After coming across this helpful post, I tried using Partial<T>
but encountered issues. Despite the following code compiling without errors:
interface Animal {
name: string;
}
interface HasConstructor {
constructor: any;
}
type OptionalAnimal = Partial<Animal> & HasConstructor;
class Dog implements OptionalAnimal {
public constructor() {
}
public breed: string;
}
The name
property ends up missing on instances of Dog:
var spot = new Dog();
spot.name = "Spot"; //ERROR: Property 'name' does not exist on type 'Dog'
To work around this inconsistency, I had to define another type and reference it like so:
type AnimalDog = Dog & Animal;
var spot: Animal = new Dog() as any;
spot.name = "Spot";
This workaround, however, doesn't allow for creating new instances of AnimalDog
properly, necessitating casting to any
to align types. As a result, I'm forced to use both AnimalDog
and Dog
in various sections of my code, leading to compile errors within Dog when dealing with Animal types.
Is there a way in typescript to indicate that a class implements an interface without explicitly listing every interface property?