Search code examples
typescriptdenochalk

Chalk won't run in Deno


The following code is from the README of the Deno Chalk library. Deno/Typescript will not let it pass:

import chalk from "https://deno.land/x/[email protected]/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!");

Output:

error: TS2339 [ERROR]: Property 'blue' does not exist on type '{ (...arguments_: any[]): string; Chalk: typeof Chalk; }'. console.log(chalk.blue("Hello world!"));

Patched:

Commenting out line 3 and it runs fine! So chalk.blue is available at runtime but invisible to the compiler??

function At runtime it's fine!


Solution

  • It's common for third-party code to have type libraries of varying quality.

    The particular module that you're importing is a JavaScript file (which does not include type information). However, there is a type declaration file accompanying it at https://deno.land/x/[email protected]/index.d.ts.

    Deno has a mechanism for cases like these, which allows you to provide a compiler hint for the module that you're importing: the @deno-types directive. Read about it here: https://deno.land/[email protected]/typescript/types#providing-types-when-importing

    You can use it like this in your case, before the import statement:

    // @deno-types="https://deno.land/x/[email protected]/index.d.ts"
    import chalk from "https://deno.land/x/[email protected]/source/index.js";
    

    A bit of context: At present, you'll find quite a few modules at deno.land/x which are simply copied directly from npm packages. Lots of these don't include types, and many still are not even in proper ESM format (using bare specifiers without import maps, etc.), making them completely incompatible with Deno. This variable quality is just the nature of using third-party software (no matter which ecosystem), and unfortunate for you as a consumer, because it increases your work of auditing your dependencies.