如何在类中实现多个接口

时间:2017-09-06 12:24:55

标签: typescript

我想在泛型类中实现这两个接口。我该怎么做?

interface first {
    name: string,
    age: number
}

interface second {
    product: string,
    available: boolean,
    amount: number
}

class generics <T>{

}

2 个答案:

答案 0 :(得分:21)

使用,分隔您要实现的接口。这给出了以下类声明:

class generics <T> implements first, second

以下是完整的代码:

interface first {
    name: string,
    age: number
}

interface second {
    product: string,
    available: boolean,
    amount: number
}

class generics <T> implements first, second {
    name: string;
    age: number;
    product: string;
    available: boolean;
    amount: number;
}

Playground link

答案 1 :(得分:-2)

通过接口在多个类中创建特定类型。

    interface Calculated{
        calculate(input1: number,input2: number): void;
     }

     class Add implements Calculated{ //addition class
         calculate(input1: number, input2: number){
             console.log("The Addition of" + " " + input1 + "+" + input2 + "=" + (input1 + input2));

         }
     }

     class Subtract implements Calculated{ //subtraction class
         calculate(input1: number, input2: number){
             console.log("The subtraction of" + " " + input1 + "-" + input2 + "=" + (input1 - input2));
         }
     }

     class Mulitiple implements Calculated{ //multiplication class
         calculate(input1: number, input2: number){
             console.log("The multiplication of" + " " + input1 + "*" + input2 + "=" + (input1 * input2));
         }
     }

     class Divide implements Calculated{ //division class
         calculate(input1: number, input2: number){
             console.log("The division of" + " " + input1 + "/" + input2 + "=" + (input1 / input2));
         }
     }  

     class Calculator{ //calculator 
         input1: number;
         input2: number;
         condition: Calculated; //interface type specification

         constructor (input1: number, input2: number, condition: Calculated) {
            this.input1 = input1;
            this.input2 = input2;
            this.condition = condition;  

            const operateObj = this.condition;
            operateObj.calculate(this.input1,this.input2);       
         }
     }

     //calculator calling....

     const calculatorObj = new Calculator(100, 75.0,new Add); //(it should be input1 & input2 & like to you perform)

     // if you need addition use Add
     // if you need subtraction use Subtract
     // if you need multiplication use Mulitiple
     // if you need division use Divide