Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor JS interop with Typescript - proper DotNet declaration import

I'm writing a Razor Class Library that incorporates JavaScript interop transpiled from TypeScript. Some code in TypeScript will reference globally available variable DotNet which gets included when Blazor libraries are initialized. I was able to find DotNet module declaration in @microsoft/dotnet-js-interop Node package (added as devDependency) and TypeScript is able to find the export when "moduleResolution": "node" is set in my tsconfig.json. However, if I do import { DotNet } from "@microsoft/dotnet-js-interop", then this import is kept in transpiled JavaScript code. I tried a few workarounds, but they didn't work:

  1. Using import type { DotNet } from "@microsoft/dotnet-js-interop" results in (TS) 'DotNet' cannot be used as a value because it was imported using 'import type'. wherever DotNet is being referenced;
  2. I cannot for my life get any results when trying things like ///<reference types/path="@microsoft/dotnet-js-interop or node_modules/@microsoft/dotnet-js-interop/dist/Microsoft.JSInterpop.d.ts"> or modifying tsconfig.json values such as paths (with "baseUrl"=".") or typeRoots. All theses result in error (TS) Cannot find name 'DotNet'.

Is there any way to properly import DotNet module declaration without polluting transpiled JavaScript code with unnecessary imports?

like image 671
jotbasan Avatar asked May 08 '26 20:05

jotbasan


1 Answers

It was tricky (lack of cohesive documentation didn't help), but I was able to figure it out myself.

The trick is to declare a variable and define its type with typeof import like so:

declare const DotNet: typeof import("@microsoft/dotnet-js-interop").DotNet;

Put this at the top of a file and you're good to go.

like image 134
jotbasan Avatar answered May 10 '26 18:05

jotbasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!