作者:青烟_I乀n-a_396 | 来源:互联网 | 2023-08-31 22:27
我有一个打字稿没有正确读取我的返回类型的问题。我正在定义一个返回类型为something | null
. 打字稿所做的是只读取something
类型,忽略空值,当我调用函数时可以返回空值。
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: [],
};
感谢所有帮助!
回答
作为结果类型string | null
,则需要启用strictNullChecks
在compilerOptions
这样的:
"compilerOptions": {
"strictNullChecks": true
}
有关更多详细信息,请参阅TypeScript 文档。