打字稿:当外部功能返回一种类型的'任何'?

发布于 2025-02-10 08:55:47 字数 2099 浏览 1 评论 0 原文

例如,函数 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
  }
}

For example, the function JSON.parse(data) returns a type of any. So if you write something like this:

const parsed = JSON.parse('example');

console.log(parsed.somethingThatDoesntExist);

No error occurs in VSCode, despite having noImplicitAny set to true in my tsconfig.json, and my .eslintrc.js having the rule '@typescript-eslint/no-explicit-any': 'error'.

I have also tried adding the following rules to my eslintrc.js, however they seem to break all TypeScript error checking:

'@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',

In an ideal world I would want this any to be presumed to be unknown, but an error would also be great.

Here is my 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',
      },
    ],
  },
};

and 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南七夏 2025-02-17 08:55:47

我认为您最好的选择是覆盖想要明确类型的任何库。通常,内置的键入(除JSON.PARSE除外),但是如果您想从外部库中修复损坏或固执的类型,这可能会有所帮助。

中的全局(或内置)

declare global {
  interface JSON {
    parse<T>(text: string, reviver?: (this: any, key: string, value: any) => T): T
  }
}

export {} //this is needed to make it a module

对于 global.d.ts 或模块的其他语法

declare module 'fooLibrary' {
  declare function bar<T>(): T
}
// IE. require('fooLibrary') or import * from ('fooLibrary')

,现在,当您尝试使用 json.parse

const foo = JSON.parse('test');
//   ^type? => unknown
const bar = JSON.parse<Record<string, any>>(...);
//   ^type? => Record<string, any>

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

declare global {
  interface JSON {
    parse<T>(text: string, reviver?: (this: any, key: string, value: any) => T): T
  }
}

export {} //this is needed to make it a module

Or a different syntax for modules

declare module 'fooLibrary' {
  declare function bar<T>(): T
}
// IE. require('fooLibrary') or import * from ('fooLibrary')

And now when you try to use JSON.parse

const foo = JSON.parse('test');
//   ^type? => unknown
const bar = JSON.parse<Record<string, any>>(...);
//   ^type? => Record<string, any>

View working example on TS Playground

牵强ㄟ 2025-02-17 08:55:47

不幸的是,我不知道编译器选项或类似的全局解决方案可以给出您想要的结果。但是,您可以制作一个断言功能,该函数在特定表达式上取消的任何:

type NotAny<T> = 0 extends 1 & T ? never : unknown
declare function assertNotAny<T extends NotAny<T>>(value: T): void

assertNotAny('"example"') // okay
assertNotAny(JSON.parse('"example"')) // error

这使用任何不能分配给从不的事实。通过制作解决从不的条件类型,您可以在传递任何时会导致类型错误。

有关更多详细信息,请参见 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:

type NotAny<T> = 0 extends 1 & T ? never : unknown
declare function assertNotAny<T extends NotAny<T>>(value: T): void

assertNotAny('"example"') // okay
assertNotAny(JSON.parse('"example"')) // error

This uses the fact that any cannot be assigned to never. By making a conditional type that resolves to never, you can cause a type error when any is passed in.

For more details, see https://stackoverflow.com/a/77385024/480608

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文