Skip to content

Default values for model properties overwrite values passed with constructor #325

@hpawe01

Description

@hpawe01

If the typescript compiler option strictPropertyInitialization is enabled (default in strict mode), it demands default values for our models, e.g.:

...
@JsonApiModelConfig({
    type: 'posts'
})
export class Post extends JsonApiModel {

    @Attribute()
    title: string = 'Placeholder';

}
...

The problem with this is, that when we (and the library) create a new model and passing the attributes through the constructor, the title of the post will still be the default string:

const post = new Post(datastore, {title: 'My first'})`;

console.log(post.title) // => "Placeholder"

The reason for this is, that the constructor of the base class (JsonApiModel), that is responsible for setting the passed attributes, is called before the default values of the extending class (Post) are set. That is just the way, typescript code is compiled to javascript (see example).

The only option (that I see) is, to use the non null assertion operator (!) for all my properties that shouldn't be undefined.

title!: string;

Does anybody has another solution for this issue?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions