I would like to create a class that has all the properties of an interface, but does not actually declare those properties itself.The interface properties are appended during the build process and WILL exist at runtime.
I found this post that pointed me in the direction of using Partial<T>...but that doesn't seem to work. The following code produces no compile errors.
interface Animal {
name: string;
}
interface HasConstructor {
constructor: any;
}
//Do this to supress this error: "Type 'Dog' has no properties in common with type 'Partial<Animal>"
type OptionalAnimal = Partial<Animal> & HasConstructor;
class Dog implements OptionalAnimal {
public constructor() {
}
public breed: string;
}
However, the name property is not available on the instance of Dog.
var spot = new Dog();
spot.name = "Spot"; //ERROR: Property 'name' does not exist on type 'Dog'
I can get around this issue by creating another type and referencing it like this:
type AnimalDog = Dog & Animal;
var spot: Animal = new Dog() as any;
spot.name = "Spot";
However, I can't construct a new instance of AnimalDog, and have to cast as any to get the types to line up, so I'm left using both AnimalDog and Dog in my code depending on the scenario. This also produces compile errors inside of Dog when referencing Animal types.
Is there a way to tell typescript that the class implements the interface, without explicitly declaring every interface property?
constructor: any? All objects have this property already ..\Is there a way to tell typescript that the class implements the interface, without explicitly declaring every interface property?No. That's what classes are for, not interfaces. Interfaces DO NOT exist at runtime. Make a class instead of an interface and extend it instead of implementing it.Doga class at all? If you create everything during the build, let it be interface as welleverythingduring the build, just tack on the missing parts from the interface. My example is not identical to our real-world scenario, butDoghas its own properties, and we actually need to runnew Dog(), requiring a concrete instance of the class.