我遇到了 Typescript 无法正确读取返回类型的问题。
我正在定义一个返回类型为 something | null
的函数。打字稿所做的就是只读取 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: [],
};
感谢大家的帮助!
答案 0 :(得分:5)
要将结果输入为 string | null
,您需要像这样在 strictNullChecks
中启用 compilerOptions
:
"compilerOptions": {
"strictNullChecks": true
}
有关详细信息,请参阅 TypeScript docs。
答案 1 :(得分:1)
这是因为您没有在 tsconfig 中将 strictNullChecks
标志设置为 true。因此 TS 不会强制执行空检查,因此对于所有意图和目的,它只是一个字符串。
看看在 this playground link 中如何关闭严格的空检查,它的行为和你看到的一样,但是一旦你 turn it on,response
的类型是 string | null
< /p>
如果这是一个新项目,我建议激活最严格的设置以获得最佳类型安全性。