typescriptvisual-studio-codenpmdeno

How do I import npm types to Deno?


I'm working in a Deno project that uses the mssql npm package. I can import it like import sql from 'npm:mssql'; and it works. The problem is that I get no types on VS Code. When I type "sql." I get no suggestions and everything I type after has type any.

If I remove that import and instead use import sql from 'npm:@types/mssql'; then I can see suggestions when I type "sql.", but it crashes when I run it because there are no actual values (I get a "Cannot find module ..." error).

And if I import both like

import sql from 'npm:mssql';
import sql from 'npm:@types/mssql';

then I get a duplicate identifier error. Is there a way to get both types and values?


Solution

  • In a classic TSC based project you can have a separate type resolution root and a source resolution root so you can have code like:

    import sql from 'mssql';
    import type { Connection } from 'mssql'; 
    

    and this would be resolved both from node_modules and node_modules/@types (assuming @types is set as a type resolution root).

    However according to the docs Deno applies a design principle of no non-standard module resolution, which (I think) means you can't have varying resolution roots.

    This does result in issues with typescript, but Deno offers a solution in your code by allowing you to have a @ts-types doc declaration. In this case you'd do:

    // @ts-types="npm:@types/mssql"
    import sql from 'npm:mssql';
    

    which will instruct Deno to include type definitions from @types/mssql

    Note: I would imagine IDEs might eventually do this implicitly but as far as I can tell this seems to be the official way of doing it right now.