【问题标题】:Typescript not reading null when returning返回时打字稿不读取null
【发布时间】:2021-04-10 06:50:06
【问题描述】:

我遇到了 Typescript 无法正确读取我的返回类型的问题。 我正在定义一个返回类型为something | null 的函数。 typescript 所做的是只读取 something 类型,忽略 null,当我调用函数时可以返回。

function nullornot(): null | string { // here is says it returns null | string
    return null
}

const response = nullornot() // but here is says it returns string

我的 tsconfig.json 文件

{
   "extends": "./tsconfig.paths.json",
   "compilerOptions": {
     "typeRoots": ["node_modules/@types", "src/@types"],
     "allowSyntheticDefaultImports": true,
     "lib": ["ESNext"],
     "moduleResolution": "node",
     "noUnusedLocals": true,
     "noUnusedParameters": true,
     "removeComments": true,
     "sourceMap": true,
     "target": "ESNext",
     "outDir": "lib"
   },
   "files": ["src/@types/graphql.d.ts"],
   "include": ["src/**/*.ts"],
   "exclude": [
     "node_modules/**/*",
     ".serverless/**/*",
     ".webpack/**/*",
     "_warmup/**/*",
     ".vscode/**/*"
   ]
}

我的 webpack.config.js 文件

module.exports = {
  context: __dirname,
  mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
  entry: slsw.lib.entries,
  devtool: slsw.lib.webpack.isLocal ? 'eval-cheap-module-source-map' : 'source-map',
  resolve: {
    extensions: ['.mjs', '.json', '.ts'],
    symlinks: false,
    cacheWithContext: false,
    plugins: [
      new TsconfigPathsPlugin({
        configFile: './tsconfig.paths.json',
      }),
    ],
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js',
  },
  optimization: {
    concatenateModules: false,
  },
  target: 'node',
  externals: [nodeExternals()],
  module: {
    rules: [
      // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
      {
        test: /\.(tsx?)$/,
        loader: 'ts-loader',
        exclude: [
          [
            path.resolve(__dirname, 'node_modules'),
            path.resolve(__dirname, '.serverless'),
            path.resolve(__dirname, '.webpack'),
          ],
        ],
        options: {
          transpileOnly: true,
          experimentalWatchApi: true,
        },
      },
      {
        test: /\.graphql?$/,
        use: [
          {
            loader: 'webpack-graphql-loader',
            options: {
              // validate: true,
              // schema: "./src/schema.graphql",
              // removeUnusedFragments: true
              // etc. See "Loader Options" below
            }
          }
        ]
      }
    ],
  },
  plugins: [],
};

感谢大家的帮助!

【问题讨论】:

    标签: node.js typescript webpack


    【解决方案1】:

    这是因为您没有在 tsconfig 中将 strictNullChecks 标志设置为 true。因此 TS 不会强制执行 null 检查,因此对于所有意图和目的而言,它只是一个字符串。

    看看this playground link 中严格的空检查是如何关闭的,它的行为与你看到的一样,但是一旦你turn it onresponse 的类型就是string | null

    如果这是一个新项目,我建议激活最严格的设置以获得最佳类型安全性。

    【讨论】:

    • 感谢它的工作!我会按照您的建议启用这些选项strictNullChecks, noImplicitAny, noImplicitThis, alwaysStrict
    【解决方案2】:

    要将结果键入为string | null,您需要在compilerOptions 中启用strictNullChecks,如下所示:

    "compilerOptions": {
      "strictNullChecks": true
    }
    

    有关详细信息,请参阅TypeScript docs

    【讨论】:

      猜你喜欢
      • 2017-06-15
      • 2019-12-06
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      相关资源
      最近更新 更多