【问题标题】:Using untyped javascript modules with Typescript: Property does not exist on type 'unknown'将无类型的 JavaScript 模块与 Typescript 一起使用:“未知”类型上不存在属性
【发布时间】:2020-11-21 10:41:47
【问题描述】:

我正在使用 Typescript 开发一个新的 Svelte 项目。我还使用了 svelte-mui 组件模块,它不是用 Typescript 编写的,也没有类型文件。每当我尝试使用一个组件时,VSCode 都会用恼人的红色曲线突出显示该组件,因为 Typescript 不知道作为对象一部分的纤细属性。该项目构建并运行良好,但我想弄清楚如何告诉 Typescript 它们是什么类型。我知道所有组件都扩展SvelteComponent,但我不知道如何告诉 Typescript。

<script>
import Button from 'svelte-mui';
</script>

<Button on:click={() => {console.log('Clicked')}}>My Button</Button>

最后一行将在编辑器中突出显示为错误。

如何告诉 Typescript Button 扩展了 SvelteComponent?

编辑:@tmdesign

我按照下面 tmdesign 提供的链接中的说明进行操作,但没有骰子。我是 Typescript 的新手,所以也许我仍然做错了什么。我最终得到了一个位于

的文件

types\svelte-mui\index.d.ts

包含

declare module 'svelte-mui' {
    import { SvelteComponent } from "svelte/internal";

    class Button extends SvelteComponent{}

    export { Button }
}

但错误仍然存​​在。

【问题讨论】:

  • 我可能应该补充一点,我可以使用 import { SvelteComponent } from 'svelte/internal'; 导入 SvelteComponent
  • @tmdesign 感谢您的链接,但错误仍然存​​在。请参阅上面的编辑。

标签: javascript typescript svelte-3


【解决方案1】:

我在使用 Svelte Material UI 时遇到了类似的错误,但解决方案应转换为 svelte-mui

首先,在tsconfig.json中配置typeRoots,让编译器在types目录下找到你的声明文件:

{
  "compilerOptions": {
     ...
    "typeRoots": [
      "./node_modules/@types",
      "./types"
    ]
  }
}

确保不要按照您提到的链接页面的建议将“类型”添加到 exclude 列表中。我认为这会阻止编译器使用您的声明文件。

然后,将types/svelte-mui/index.d.ts 更新为:

declare module 'svelte-mui' {
  import type { SvelteComponent } from "svelte";

  class Button extends SvelteComponent { }
  export default Button;
}

重新启动 VSCode 或运行“Svelte:重新启动语言服务器”命令以确保它使用新配置。您的 Button 组件不应再显示错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 2018-08-17
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 2016-08-21
    • 2019-06-28
    • 1970-01-01
    相关资源
    最近更新 更多