打字稿:当外部功能返回一种类型的'任何'?
例如,函数 json.parse(data)
返回一种的类型
。因此,如果您编写类似的内容:
const parsed = JSON.parse('example');
console.log(parsed.somethingThatDoesntExist);
尽管在我的
中设置为 try> tsconfig.json ,但在VSCODE中没有错误,但在vscode中没有错误。代码> .eslintrc.js 具有规则'@typescript-eslint/no-explitic-yan':'错误'
。
我还尝试过将以下规则添加到我的 eslintrc.js
,但是它们似乎打破了所有打字稿错误检查:
'@typescript-eslint/no-unsafe-call': 'error',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-argument': 'error',
'@typescript-eslint/no-unsafe-assignment': 'error',
在理想的世界中,我希望此任何要预测的
为未知
,但错误也很棒。
这是我的 eslintrc.js
:
module.exports = exports = {
root: true,
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
parserOptions: {
ecmaVersion: 2021,
},
extends: ['plugin:@typescript-eslint/recommended', 'prettier', 'plugin:prettier/recommended'],
rules: {
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/no-unsafe-call': 'error',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-argument': 'error',
'@typescript-eslint/no-unsafe-assignment': 'error',
'@typescript-eslint/no-explicit-any': 'error',
'prettier/prettier': [
'error',
{
trailingComma: 'all',
tabWidth: 2,
semi: true,
singleQuote: true,
bracketSpacing: true,
printWidth: 120,
endOfLine: 'auto',
},
],
},
};
和 tsconfig.json
:
{
"compilerOptions": {
"strict": true,
"target": "es6",
"module": "commonjs",
"lib": [
"es6",
"ES2021.String"
],
"esModuleInterop": true,
"moduleResolution": "node",
"outDir": "../build/",
"rootDir": ".",
"resolveJsonModule": true,
"composite": true,
"types": [],
"noImplicitAny": true,
"noImplicitThis": true,
"noImplicitReturns": true
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您最好的选择是覆盖想要明确类型的任何库。通常,内置的键入(除JSON.PARSE除外),但是如果您想从外部库中修复损坏或固执的类型,这可能会有所帮助。
中的全局(或内置)
对于
global.d.ts
或模块的其他语法,现在,当您尝试使用
json.parse
I think your best option would be to override any libraries where you want an explicit type. Generally the built-ins are typed well (with the exception of JSON.parse), but this could be helpful if you want to fix a broken or stubbed type from an external library.
For global (or built-ins) in a
global.d.ts
Or a different syntax for modules
And now when you try to use
JSON.parse
View working example on TS Playground
不幸的是,我不知道编译器选项或类似的全局解决方案可以给出您想要的结果。但是,您可以制作一个断言功能,该函数在特定表达式上取消的任何:
这使用
任何
不能分配给从不
的事实。通过制作解决从不
的条件类型,您可以在传递任何时会导致类型错误。有关更多详细信息,请参见 https://stackoverflow.com/a/777385024/480608
Unfortunately, I don't know of a compiler option or similarly global solution that gives the result you want. However, you can craft an assertion function that disallows
any
on a specific expression:This uses the fact that
any
cannot be assigned tonever
. By making a conditional type that resolves tonever
, you can cause a type error whenany
is passed in.For more details, see https://stackoverflow.com/a/77385024/480608