typescriptmonaco-editor

Monaco Editor & Typescript: How to add global types?


How can I instruct the Monaco editor that a set of types is global? Here's what I've tried. With the setup below, I can successfully write import type { Foo } from "my-lib"; into the Monaco editor. However, I want to allow the types in my-lib to be global so that the script being edited within Monaco does not have to explicitly import anything.

// setup compiler options
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
    target: monaco.languages.typescript.ScriptTarget.ES2016,
    allowNonTsExtensions: true,
    moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
    module: monaco.languages.typescript.ModuleKind.CommonJS,
    noEmit: true,
    typeRoots: ["node_modules/@types"],
    types: ["my-lib"] // <=== NOTE THIS
});

// define my-lib
monaco.languages.typescript.typescriptDefaults.addExtraLib(
    "export interface Foo { foo: number; }",
    "file:///node_modules/@types/my-lib/index.d.ts"
);

// create model
const model = monaco.editor.createModel(
    "const o: Foo = { foo: 23 };", // <=== this code will have an error in the Monaco editor
    "typescript",
    monaco.Uri.parse(`file:///main.ts`)
);

// create the editor
const editor = monaco.editor.create(document.getElementById("container"), { model });

Monaco Editor Playground


Solution

  • I couldn't find an explanation why, but removing the export keyword from the source text makes Monaco accepting code which uses this interface.