【问题标题】:ESLint: Unsafe assignment of an `any` and Unsafe call of an `any` typed valueESLint:“any”的不安全分配和“any”类型值的不安全调用
【发布时间】:2023-04-05 03:12:01
【问题描述】:

考虑以下测试代码:

import { isHtmlLinkDescriptor } from '@remix-run/react/links'
import invariant from 'tiny-invariant'
import { links } from '~/root'

it('should return a rel=stylesheet', () => {
  const response = links()

  invariant(isHtmlLinkDescriptor(response[0]))

  expect(response[0].rel).toBe('stylesheet')
})

和实施:

import { LinksFunction } from 'remix'
import tailwindProdUrl from '~/styles/tailwind.css'

export const links: LinksFunction = () => {
  const href =
    process.env.NODE_ENV !== 'production' ? './tailwind.css' : tailwindProdUrl

  return [{ rel: 'stylesheet', href }]
}

其中LinksFunction 定义为herehere

为什么 ESLint 抱怨“any 值的分配不安全”。和“any 类型值的不安全调用。”在下面一行?

const response = links()

【问题讨论】:

    标签: javascript typescript eslint


    【解决方案1】:

    您在第二个 sn-p 中导入错误。应该是:

    import { LinksFunction } from '@remix-run/server-runtime';
    

    或者,如果您使用的是 TypeScript 3.8 或更高版本:

    import type { LinksFunction } from '@remix-run/server-runtime';
    

    LinksFunction 仅用作您显示的代码中的一种类型,这意味着 TypeScript 编译器在某些情况下仍然可以成功编译您的模块,尽管缺少类型定义。

    【讨论】:

    • 谢谢,但这并不能解决问题。 LinksFunction 可以从 remix 导入,因为这个包从其他包中导出所有内容。无论如何,我已经按照您的建议更改了我的代码,但仍然存在 lint 问题。
    • 另一方面,importimport type 真的会给我那个 lint 错误吗?问是因为如果是这样的话,我发现该消息确实具有误导性。
    • 您使用的是什么版本的混音?我从 MDM 安装了 1.0.6,里面的 index.d.ts 引用了 npm 包中未包含的文件:“./client”、“./server”和“./platform”。
    • 嗯,不是 importimport type 有区别,而是 LinksFunction 只是一个类型,而不是类的名称或另一个 JavaScript 标识符。
    • 我明白这一点,我刚刚在我的 tsconfig 中添加了一条规则,以确保我使用import type 对 iport 类型进行 onlu,但这并不是说它不起作用。我也在使用remix 1.0.6。顺便说一句,我的 VSCode 向我展示了 TS 正确推断 response 的类型。在响应下自动完成方法也可以正常工作,但是 ESLint 给了我这个错误。
    猜你喜欢
    • 1970-01-01
    • 2022-12-18
    • 2022-10-01
    • 2021-07-27
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 2022-08-04
    相关资源
    最近更新 更多