FreeAntiVirus
FreeAntiVirus

Reputation: 159

eslint No Unsafe Assignment Rule

I have this HTTP test that tests simple successful output from a function called echo.

describe('HTTP tests using Jest', () => {
  test('Test successful echo', () => {
    const res = request(
      'GET',
            `${url}:${port}/echo`,
            {
              qs: {
                echo: 'Hello',
              }
            }
    );

    const bodyObj = JSON.parse(res.body as string);
    expect(res.statusCode).toBe(OK);
    expect(bodyObj).toEqual('Hello');
  });

When I try to lint I get @typescript-eslint/no-unsafe-assignment error on the line below

const bodyObj = JSON.parse(res.body as string);

Is there a way to ignore this rule entirely? How can I fix the issue?

Upvotes: 0

Views: 5697

Answers (1)

Fcmam5
Fcmam5

Reputation: 6922

You can either ignore for this line with:

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const bodyObj = JSON.parse(res.body as string);

Or for the whole file:

/* eslint-disable @typescript-eslint/no-unsafe-assignment*/

Or if you want to ignore this rule entirely, you can check your eslint config and set

{
  "rules": {
    "@typescript-eslint/no-unsafe-assignment": "warn" // or "off" if you want to disable it
  }
}

But if you want to actually fix this error, you should avoid assigning a variable of type any to a variable, in this case, you have JSON.parse(), for example, you can set unknown as type:

const bodyObj = JSON.parse(res.body as string) as unknown;

Or maybe better if you set your actual res.body type

const bodyObj = JSON.parse(res.body as string) as MyTypeOrInterface;

Upvotes: 1

Related Questions