Skip to content

[API Proposal]: Generate d.ts file from JSExport attributes #74233

@yamachu

Description

@yamachu

Background and motivation

JSExport Attribute can make .NET static methods accessible to JavaScript side.

However, access to such methods requires the correct namespace, class name, and method name, and may result in access to invalid objects.

By outputting d.ts when generating JavaScript Interop source, it is possible to type exported objects, which will improve the development experience.

API Proposal

dotnet.d.ts

declare type APIType = {
    runMain: (mainAssemblyName: string, args: string[]) => Promise<number>;
    runMainAndExit: (mainAssemblyName: string, args: string[]) => Promise<number>;
    setEnvironmentVariable: (name: string, value: string) => void;
-   getAssemblyExports(assemblyName: string): Promise<any>;
+   getAssemblyExports<T = any>(assemblyName: string): Promise<T>;

dotnet.g.d.ts

import "@microsoft/dotnet-runtime";

declare module "@microsoft/dotnet-runtime" {
    interface AssemblyExports {
        MyClass: {
            Greeting: () => void;
        }
    }
}

API Usage

main.mts

import { dotnet, AssemblyExports } from "@microsoft/dotnet-runtime";

const { getAssemblyExports } = await dotnet
    .withDiagnosticTracing(false)
    .create();

const config = getConfig();
const exports = await getAssemblyExports<AssemblyExports>(config.mainAssemblyName);
const text = exports.MyClass.Greeting();
console.log(text);

wasmconsole.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
    <WasmMainJSPath>main.mjs</WasmMainJSPath>
    <OutputType>Exe</OutputType>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
    <JSInteropTypeDefinitionOutputDir>./types</JSInteropTypeDefinitionOutputDir>
  </PropertyGroup>

  <ItemGroup>
    <CompilerVisibleProperty Include="JSInteropTypeDefinitionOutputDir" />
  </ItemGroup>
</Project>

Alternative Designs

PoC: https://github.com/yamachu/NetWebAssemblyTSTypeGenerator

Risks

  • It may not work well in JSDoc
  • It will not work if the package.json does not contain a runtime dependency

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions