Home > Software design >  VSCode Eslint Error no-unsafe-assignment Incorrectly Displayed
VSCode Eslint Error no-unsafe-assignment Incorrectly Displayed

Time:01-27

This is a weird issue involving @typescript-eslint/no-unsafe-assignment. I had a typescript file, call it oldmodel.ts, and in my VSCode IDE, when I load the file, the following does NOT produce any error in my ESlint VSC terminal:

export interface ITestObject {
  createDate?: Date,
}

export class TestObject implements ITestObject {
  createDate?: Date;

  constructor(options: ITestObject = {}) {
    this.createDate = (options.createDate instanceof Date || !isNaN(Date.parse(options.createDate || ''))) ? new Date(options.createDate || '') : undefined;
  }
}

If I copy and paste this same exact code in a newly created newmodel.ts file, existing in the same folder as oldmodel.ts, my VSCode produces that unsafe-assignment error for the line beginning with this.createDate. Does anybody know how/why this is happening?

CodePudding user response:

Ok, I cannot remember who suggested this since he deleted his comment, but I followed his suggestion and it seemed to work. So what I did was in the newmodel.ts file, I created another class that referenced the concerning class:

interface ISampleResponse {
  testObject?: TestObject
}

export class SampleResponse implements ISampleResponse {
  testObject?: TestObject

  constructor(options: ISampleResponse = {}) {
    this.testObject = new TestObject(options.testObject);
  }
}

Then, in another file, say an injectable service for example, I proceeded to import that response class in the file:

import { SampleResponse } from '../models/newmodel.ts';

After I saved that file, I went back to newmodel, went to the line that had that eslint error, modified it just so it could channel a change, and then the error disappeared! It may simply be that there has to be a reference made to that file with that class in order for the error to go away.

I need to verify this a couple more times, but if it still works, I'll mark this as an answer for everyone to follow.

CodePudding user response:

I guess that until you don't declare your new component "TestObject" in your appropiate module, the file code could show some errors sometimes.

Can you test if when you add "TestObject" to the declaration section of themodule where is the new file, the errors disappear?

EDIT: I could think in 2 different causes/reasons:

  1. The oldmodel file name was "test-object.ts" and match with the class name ("TestObject"), but the new file (new-object.ts") doesn't match with "TestObject".

  2. You are calling the oldmodel as TestObject, and the new one as well. Then, the angular system "suffer" a problem, so it is showing that error.

Does any of this new one answers make sense to you? Could you test it?

  •  Tags:  
  • Related