This seems like a bug to me, but I'm relatively new to Typescript, so I'm assuming I'm just doing something wrong.
Given:
interface IParams {
id?: number;
type?: string;
}
class Test {
id: number;
type: string;
constructor({
id = 0,
type = ''
}: IParams = {}) {
this.id = id; // "Assigned expression type number | undefined is not assignable to type number"
this.type = type;
}
}
I also tried this but got the same result:
constructor({
id = 0,
type = ''
}: IParams = { id: 0, type: '' }) { }
If I change the problematic line to this, it stops complaining:
this.type = id ?? 0;
But that feels hacky since that's the entire purpose of default arguments.
I can also make the properties in IParams
non-optional, but then I'm required to pass all arguments to the constructor, totally missing the mark of default values.
Why does Typescript seemingly ignore the default arguments?