I need to set strict
to true in my tsconfig.json
, but this is causing issues. For example, required fields in models that aren't set are causing typescript errors. Is there any way to have the strictness of tsc with loopback 4?
Taking the example code in their documentation:
@model()
export class Todo extends Entity {
@property({
type: 'number',
id: true,
})
id?: number;
@property({
type: 'string',
required: true,
})
title: string;
@property({
type: 'string',
})
desc?: string;
@property({
type: 'boolean',
})
isComplete: boolean;
@belongsTo(() => TodoList)
todoListId: number;
getId() {
return this.id;
}
constructor(data?: Partial<Todo>) {
super(data);
}
}
If you turn on strict
in the tsconfig.json
compiler options, you would get errors such as the following:
Property 'title' has no initializer and is not definitely assigned in the constructor.
Edit: I'm hoping for a way that doesn't involve having a default.
Edit2: After looking at the code again, I figured the following actually works.
constructor(data: Todo) {
super(data);
this.title = data.title;
this.isComplete = data.isComplete;
}
Hello from the LoopBack team 👋
Good catch! We haven't considered this aspect when designing our model classes.
I think this problem is triggered by strictPropertyInitialization
setting. Quoting from TypeScript docs:
Ensure non-undefined class properties are initialized in the constructor.
I can see how our current type definitions allow developers to create model instances that are not valid because some of the required properties were not initialized.
Could you please open a GitHub issue in our project so that we can further discuss how to fix this problem?
In the meantime, can you try to disable strictPropertyInitialization
in your tsconfig.json
?