简体   繁体   中英

not able to set property of interface type in typescript

I am beginner in typescript programming not able to set property interface type so please guide me about that.

interface addition { 
    num1: number;
    num2: number;
    add(num1:number, num2:number): number;
}

class Calculator implements addition{
    num1: number;
    num2: number;
    adds: addition;   //

    add(num1: number, num2: number): number { 
        return num1 + num2;
    }    

    sub(num1: number, num2: number): number { 
        let sk: addition = new Calculator()
        console.log(sk.add(2, 3)); 
        this.adds.num1=12;   // showing error here Uncaught TypeError: Cannot set property 'num1' of undefined
        console.log(this.adds.num1)
        return num1-num2
    }
}

let cal = new Calculator();
console.log(cal.sub(2, 3));

You did not initialize the adds field in the declaration. So before using it the method sub you need to initialize it:

 this.adds = //initialize with a value before using it in the next line.
 this.adds.num1=12;

It's not clear what the adds in Calculator is meant to be, but nothing in your code creates an addition object and assigns it to adds , so adds is undefined , and you can't access properties on undefined . Just declaring the property for it doesn't create it. You have to either create one or receive one. (But I suspect you don't want adds at all.)


FWIW:

The code in Calculator seems odd. It declares properties it never uses (and doesn't need, from the apparent API it provides). What are the adds , num1 , and num2 properties for? You're accepting the numbers as parameters to add and sub , and Calculator itself is the addition object.

Without those properties, it would be rather simpler:

interface Addition { 
    add(num1:number, num2:number): number;
}
class Calculator implements addition {
    add(num1: number, num2: number): number { 
        return num1 + num2;
    }    

    sub(num1: number, num2: number): number { 
        return num1 - num2;
    }
}

Not sure, what you're trying to achieve, but I think a proper design would be:

interface Addition {
    add(num1: number, num2: number): number;
}

interface Subtraction {
    sub(num1: number, num2: number): number;
}

class Calculator implements Addition, Subtraction {

    add(num1: number, num2: number): number {
        return num1 + num2;
    }

    sub(num1: number, num2: number): number {
        return num1 - num2
    }
}

let cal = new Calculator();
console.log(cal.add(1, 2));
console.log(cal.sub(2, 3));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM