Hacen Selahy
Hacen Selahy

Reputation: 79

Can't use function variable in TypeScript

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; }'.

Upvotes: 1

Views: 339

Answers (3)

Igor Polyakov
Igor Polyakov

Reputation: 31

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

Upvotes: 2

yonexbat
yonexbat

Reputation: 3012

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;

Upvotes: 1

Jeto
Jeto

Reputation: 14927

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);

Upvotes: 2

Related Questions