'Why is Buffer assignment triggering an unsafe assignment error?
I have a TypeScript project that is leveraging ESLint. I have a class that utilizes a Buffer as a class attribute. I want to be able to set the buffer as part of construction.
example.ts
export class Example {
public myBuffer: Buffer
public constructor(myBuffer: Buffer) {
this.myBuffer = myBuffer
}
}
This block yields the following linter error:
5:3 error Unsafe assignment of an `any` value @typescript-eslint/no-unsafe-assignment
What is causing TypeScript to interpret this typed parameter as any
? Do I need to somehow import the Buffer
type?
As shown in this picture, my IDE does detect that "myBuffer" is of type Buffer
:
My Dev Dependencies
"devDependencies": {
"@babel/cli": "^7.10.5",
"@babel/core": "^7.8.7",
"@babel/eslint-parser": "^7.17.0",
"@babel/node": "^7.8.7",
"@babel/plugin-proposal-class-properties": "^7.8.3",
"@babel/preset-env": "^7.8.7",
"@babel/register": "^7.8.6",
"@jest/console": "^25.1.0",
"@tsconfig/node16": "^1.0.2",
"@typescript-eslint/eslint-plugin": "^5.23.0",
"@typescript-eslint/parser": "^5.23.0",
"eslint": "^8.15.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-airbnb-typescript": "^17.0.0",
"eslint-import-resolver-alias": "^1.1.2",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-sort-exports": "^0.6.0",
"jest": "^25.1.0",
"nock": "^12.0.2",
"rimraf": "^3.0.2",
"typescript": "^4.6.4"
}
Solution 1:[1]
Silly me!
The issue is that I had not added @types/node
as a project dependency. Since Buffer
exists within Node (rather than TypeScript) the type was not defined when linting without that addition.
Running yarn add --dev @types/node
(or npm install @types/node --save-dev
) does the trick.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | slifty |