实施大型界面 [英] Implementing large interface

查看:82
本文介绍了实施大型界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个具有较大接口的库

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?

推荐答案

是的,如果实现该接口,则必须重新声明所有字段.您可以通过创建创建实现该接口的类的函数来解决.该实现实际上不会添加任何代码或字段,它只会声明这样做,如果接口仅包含可以工作的字段,尽管这些字段将保持未初始化,但是如果它具有方法,则它们将是未定义的:

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;

在打字稿2.8中,您还可以定义autoExtend来删除方法,以避免带有方法的接口出现潜在错误:

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(){

    }
} 

这篇关于实施大型界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆