Fran b
Fran b

Reputation: 3036

Typescript error: A private property is missing?

I have a class with a private property but when I try to create an array with this elements I get the following error:

error TS2322: Type '{ "id": number; "totalTime": number; "team": { "id": number; "name": string; }; }[]' is not assignable to type 'Training[]'.
[0]   Type '{ "id": number; "totalTime": number; "team": { "id": number; "name": string; }; }' is not assignable to type 'Training'.
[0]     Property 'remainingTime' is missing in type '{ "id": number; "totalTime": number; "team": { "id": number; "name": string; }; }'

Array class:

import { TEAMS } from './mock-teams';
import { Training } from './training';

export var TRAININGS: Training[] = [ 
    {"id": 0, "totalTime": 60, "team": {"id": TEAMS[0]['id'], "name": TEAMS[0]['name'] } },
    {"id": 1, "totalTime": 60, "team": {"id": TEAMS[0]['id'], "name": TEAMS[0]['name'] } }
];

Training class:

export class Training {
    private remainingTime: number = 0;

    constructor(
        public id: number,
        public totalTime: number,
        public team?: Team) {
    }   
}

I don't understand why typescript is complaining about a private property which even is not in the constructor.

Upvotes: 3

Views: 6960

Answers (1)

Abdulrahman Alsoghayer
Abdulrahman Alsoghayer

Reputation: 16540

The way you did, you are creating an array of type Object[]. What you need to do is call the constructor like below to tell the transpiler you are creating a Training object:

import { TEAMS } from './mock-teams';
import { Training } from './training';

export var TRAININGS: Training[] = [ 
    new Training(0,60, {"id": TEAMS[0]['id'], "name": TEAMS[0]['name'] }),
    new Training(1,60, {"id": TEAMS[0]['id'], "name": TEAMS[0]['name'] })
];

Upvotes: 1

Related Questions