问题
I am using a library that has a large interface
interface IOrder{
cutomerId: number;
deliveryAddress1: string;
// and lots of properties...
}
And I want to implement a class extending it.
Just want to confirm that it is necessary to re-declare all the properties.
class Order implements IOrder{
cutomerId: number;
/* error: Class 'Order' incorrectly implements interface 'IOrder'.
Property 'deliveryAddress1' is missing in type 'Order'
*/
}
Of course, methods need to be implemented but I find re-declaring the properties redundant. Am I missing something?
回答1:
Yes you have to redeclare all the fields if you implement the interface. You can do a workaround by creating a function that creates a class that implements the interface. The implementation will not actually add any code or fields it will just declare that it does so if the interface contains only fields it works although the fields will remain uninitialized, but if it has methods they will be undefine:
function autoExtend<T>(): new () => T {
return class {} as any
}
class Order extends autoExtend<IOrder>() {
}
var cc = new Order();
cc.cutomerId = 0;
In typescript 2.8 you could also define autoExtend
to remove methods, to avoid potential errors for interfaces with methods:
type NonMethodKeys<T> = ({[P in keyof T]: T[P] extends Function ? never : P } & { [x: string]: never })[keyof T];
type RemoveMethods<T> = Pick<T, NonMethodKeys<T>>;
function autoExtend<T>(): new () => RemoveMethods< T> {
return class {} as any
}
class Order extends autoExtend<IOrder>() implements IOrder {
// Must define method
method(){
}
}
回答2:
You need re-declare all the properties. Because the interface binds the properties of the implementation class
class Order implements IOrder{
cutomerId: number;
deliveryAddress1: string;
/*all properties of interface ...*/
}
来源:https://stackoverflow.com/questions/49189557/implementing-large-interface