简体   繁体   English

为什么缓冲区分配会触发不安全的分配错误?

[英]Why is Buffer assignment triggering an unsafe assignment error?

I have a TypeScript project that is leveraging ESLint.我有一个利用 ESLint 的 TypeScript 项目。 I have a class that utilizes a Buffer as a class attribute.我有一个使用Buffer作为类属性的类。 I want to be able to set the buffer as part of construction.我希望能够将缓冲区设置为构造的一部分。

example.ts例子.ts

export class Example {
    public myBuffer: Buffer

    public constructor(myBuffer: Buffer) {
        this.myBuffer = myBuffer
    }
}

This block yields the following linter error:此块产生以下 linter 错误:

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 ?是什么导致 TypeScript 将此类型化参数解释为any Do I need to somehow import the Buffer type?我需要以某种方式导入Buffer类型吗?

As shown in this picture, my IDE does detect that "myBuffer" is of type Buffer :如图所示,我的 IDE 确实检测到“myBuffer”的类型为Buffer

我的 IDE 的屏幕截图

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"
  }

Silly me!傻我!

The issue is that I had not added @types/node as a project dependency.问题是我没有添加@types/node作为项目依赖项。 Since Buffer exists within Node (rather than TypeScript) the type was not defined when linting without that addition.由于Buffer存在于 Node(而不是 TypeScript)中,因此在没有添加的情况下进行 linting 时未定义类型。

Running yarn add --dev @types/node (or npm install @types/node --save-dev ) does the trick.运行yarn add --dev @types/node (或npm install @types/node --save-dev )就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM