【问题标题】:Chalk won't run in DenoChalk 不会在 Deno 中运行
【发布时间】:2021-11-30 22:43:42
【问题描述】:

以下代码来自 Deno Chalk 库的 README。 Deno/Typescript 不会让它通过:

import chalk from "https://deno.land/x/chalk_deno@v4.1.1-deno/source/index.js";
// Run this in debugger and it's fine but it won't compile:
console.log(chalk.blue("Hello world!"));
console.log(eval("typeof chalk.blue"), "At runtime it's fine!");

输出:

错误:TS2339 [错误]:类型 '{ (...arguments_: any[]): string; 上不存在属性 'blue'粉笔:粉笔类型; }'。 console.log(chalk.blue("Hello world!"));

已修补:

注释掉第 3 行,它运行良好!那么chalk.blue 在运行时可用但对编译器不可见??

function 在运行时就可以了!

【问题讨论】:

    标签: typescript deno chalk


    【解决方案1】:

    第三方代码具有不同质量的类型库是很常见的。

    您要导入的特定模块是一个 JavaScript 文件(不包括类型信息)。但是,在 https://deno.land/x/chalk_deno@v4.1.1-deno/index.d.ts 处有一个类型声明文件。

    Deno 为此类情况提供了一种机制,它允许您为要导入的模块提供编译器提示:@deno-types 指令。在这里阅读:https://deno.land/manual@v1.14.3/typescript/types#providing-types-when-importing

    您可以在导入语句之前像这样使用它:

    // @deno-types="https://deno.land/x/chalk_deno@v4.1.1-deno/index.d.ts"
    import chalk from "https://deno.land/x/chalk_deno@v4.1.1-deno/source/index.js";
    

    一些背景知识:目前,您会在 deno.land/x 找到相当多的模块,它们只是直接从 npm 包中复制而来。其中很多不包含类型,而且很多甚至都不是正确的 ESM 格式(使用没有导入映射的裸说明符等),这使得它们与 Deno 完全不兼容。这种可变质量只是使用第三方软件的本质(无论是哪个生态系统),对于作为消费者的您来说是不幸的,因为它增加了您审核依赖项的工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-24
      • 2021-07-19
      • 2021-03-13
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多