-1

I have this error when I try to assign an empty value to an array whose type was already declared. Here is the code that causes the error,

export interface EmiCalculator {
    emi: number;
    months: number;
    position: number;
    principal: number;
    roi: number;
}

Below is the line that produces the error,

emiResults: EmiCalculator = [];

How can I assign an empty array to a property whose type was already declared.

anonymous
  • 1,499
  • 2
  • 18
  • 39

3 Answers3

3

EmiCalculator is an object, [] is an array. You probably want an array of EmiCalculator which can be written as EmiCalculator[] or Array<EmiCalculator>

export interface EmiCalculator {
    emi: number;
    months: number;
    position: number;
    principal: number;
    roi: number;
}
const emiResults: EmiCalculator[] = [];

Playground Link

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
1

You are assign an array to an object.

An Interface essentially define the structure for an object, so you can't assign an array to an object.

What you might be looking for is

emiResults: Array<EmiCalculator> = [];
Nicolas
  • 8,077
  • 4
  • 21
  • 51
-1

When you write

emiResults: EmiCalculator = [];

you are assigning an empty array to a variable emiResults whose type is defined to be EmiCalculator.

Interface defines the structure of an object. So the type of emiResults is object. But you are assigning an array.

You may want to do either of the following.

let emiResults: EmiCalculator[] = [];

or you can use the Typescript generic syntax,

let emiResults: Array<EmiCalculator> = [];