1

I have this and I can't use the method in the class because of the error shown below.

class Product {
    a:number
    b:number
    get total() {
        return this.a * this.b;
    }
}

var product: Product={
    a:2,
    b:3
}

The error:

Type '{ a: number; b: number; }' is not assignable to type 'Product'. Property 'total' is missing in type '{ a: number; b: number; }'.

1
  • This is typescript, not javascript (changed the tag accordingly). Commented Oct 5, 2018 at 17:40

3 Answers 3

2

You should probably use a constructor instead:

class Product {
    constructor(private a: number, private b: number) {}

    get total(): number {
        return this.a * this.b;
    }
}

let product: Product = new Product(2, 3);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. forever gratiful. Mr Jeto
2

Do not confuse with TypeScript. Use the contructor like this:

class Product {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }

  total() {
    return this.a * this.b;
  }
}

var product = new Product(2, 3);
console.log(product.total());

1 Comment

Thank you very much. Forever gratiful Mr Igor Ployakov
1

Yes, the object can not be a product because the function total is missing. Better use the new operator.

const x = new Product();
x.a = 3;
x.b = 5;

1 Comment

Thank you very much. Forever gratiful Mr Yonexbat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.