Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 294
Fran b Avatar asked Dec 05 '25 09:12

Fran b


1 Answers

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'] })
];
like image 103
Abdulrahman Alsoghayer Avatar answered Dec 06 '25 23:12

Abdulrahman Alsoghayer