Error instantiating Typescript Class (Error not a constructor) -
i new typescript , having trouble basic class instantiation.
i have namespace recordsservice class record declared inside of it. want able create records within recordsservice, access them via public methods other methods , such.
export namespace recordsservice { let records: array<record> = new array(); function init () { let record1 = new record(new date(), 1); } init(); export function getallrecords() { return records; } class record { constructor (public date: date, public id: number) { this.date = date; this.id = id; } } }
the above doesn't throw transpiling error when ran console error below
typeerror: record not constructor(…)
line errors let record1 = new record(new date(), 1);
how can create new record in case?
plunker, view console log see error: https://plnkr.co/edit/fnk8b1zwa5hl3i7wantq?p=preview
you need move record
class above init
function:
class record { constructor (public date: date, public id: number) { this.date = date; this.id = id; } } let records: array<record> = new array(); function init () { let record1 = new record(new date(), 1); } init();
or call init
function after definition of record
:
let records: array<record> = new array(); function init () { let record1 = new record(new date(), 1); } export function getallrecords() { return records; } class record { constructor (public date: date, public id: number) { this.date = date; this.id = id; } } init();
the reason why happens javascript interpreted language, interpreter parses code line after other, , reaches init()
part (in original code) before interpreted record
class.
the content of init
function isn't interpreted until execute function why it's safe have before class definition , execute afterwards.
also, if you're doing this:
constructor (public date: date, public id: number)
then there's no need this:
this.date = date; this.id = id;
it's either:
class record { constructor (public date: date, public id: number) {} }
or
class record { public date: date; public id: number; constructor (date: date, id: number) { this.date = date; this.id = id; } }
Comments
Post a Comment