0

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?

ken
  • 3,650
  • 1
  • 30
  • 43
  • Your first code does not result in the error to me – CertainPerformance Dec 23 '20 at 17:25
  • 1
    Does this answer your question? [Setting default value for TypeScript object passed as argument](https://stackoverflow.com/questions/23314806/setting-default-value-for-typescript-object-passed-as-argument) – Terry Dec 23 '20 at 17:25
  • @Terry the accepted 'answer' is the code I have above, so no, it does not. Also note the accepted answer is for TS 1.5 which is over 5 years old (current is v4). My code was tested on v3 and v4. Thank you though. – ken Dec 23 '20 at 17:44
  • @CertainPerformance you may be on to something, according to the TS playground (typescriptlang.org) there are no problems with the original code. However, my IDE is generating errors. Perhaps this is an IDE problem... will investigate. – ken Dec 23 '20 at 17:48
  • I'm going to blame WebStorm (or the way I have it configured), since neither typescriptlang.org nor VSCode complain. Thanks all! – ken Dec 23 '20 at 18:29
  • So the duplicate question is indeed relevant and it’s your IDE that was problematic. – Terry Dec 23 '20 at 21:25

0 Answers0