【问题标题】:Nullable return type not working in Typescript可空返回类型在 Typescript 中不起作用
【发布时间】:2022-10-07 14:51:25
【问题描述】:

鉴于此代码

export interface ICollectionService {
  get(id: string): Promise<Collection | null>;
}

const collection = await collectionService.get(collectionAddress);

现在我在 IDE 中显示的 collection 变量是 Collection 类型 不像我预期的那样Collection | null

不确定这是否与 eslint 有关?

这是我的.eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2021: true
  },
  extends: [\'eslint:recommended\', \'plugin:@typescript-eslint/recommended\'],
  overrides: [],
  parser: \'@typescript-eslint/parser\',
  parserOptions: {
    ecmaVersion: \'latest\',
    sourceType: \'module\'
  },
  plugins: [\'@typescript-eslint\'],
  rules: {}
};
  • 你的 tsconfig 是什么?如果您不是在严格模式下每个类型都可以为空,那么Collection | nullCollection 是一样的。
  • 在 tsconfig/eslintric.compilerOptions 中添加 \"strictNullChecks\": true 。

标签: typescript visual-studio-code eslint


【解决方案1】:

您需要将tsconfig.json 中的compilerOptions.strictNullChecks 标志设置为true

{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

compilerOptions.strictNullChecks 的默认值为false

【讨论】:

    猜你喜欢
    • 2020-07-23
    • 2016-02-10
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 2020-09-16
    • 2016-05-30
    • 1970-01-01
    相关资源
    最近更新 更多