gpt4 book ai didi

node.js - 返回时 typescript 不读取null

转载 作者:行者123 更新时间:2023-12-04 15:57:49 25 4
gpt4 key购买 nike

我遇到了 Typescript 无法正确读取我的返回类型的问题。我正在定义一个返回类型为 something | 的函数空。而 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

Function declaring

Function call

我的 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: [],
};

感谢大家的帮助!

最佳答案

将结果键入为 string | null,你需要像这样在compilerOptions中启用strictNullChecks:

"compilerOptions": {
"strictNullChecks": true
}

TypeScript docs了解更多详情。

关于node.js - 返回时 typescript 不读取null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65563333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com