Writing TypeScript in Monaco Editor

Implementing a TypeScript editor using Monaco involves more than just setting the language. This post covers how to configure type declarations and other essential editor settings.

Jan 20, 2024 · 1 min read · 147 Words · -Views -Comments · Digital Life
Monaco-Editor TypeScript Web-Editor 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

    Providing a high-quality TypeScript editing experience in Monaco Editor on the web requires specific configurations. Here are some key tips:

    1. Set the Language to TypeScript

    When initializing the editor instance, ensure the language is set correctly:

    monaco.editor.create(document.getElementById('container'), {
        value: "const x: number = 10;",
        language: 'typescript'
    });
    

    2. Add Custom Type Declarations (Typings)

    To provide IntelliSense for external libraries or custom interfaces, use addExtraLib. This allows the editor to recognize types that aren’t defined in the current file:

    monaco.languages.typescript.typescriptDefaults.addExtraLib([
        'declare class MyLibrary {',
        '    static doSomething(): void;',
        '}',
    ].join('\n'), 'filename/to/mylib.d.ts');
    

    3. Essential Editor Settings

    Common UI settings that improve the developer experience:

    • Minimap: Toggle the code overview on the side.
    • Theme: Switch between ‘vs’ (light), ‘vs-dark’, or ‘hc-black’.
    • Automatic Layout: Enable automaticLayout: true so the editor resizes with its container.

    These configurations transform a basic text area into a powerful IDE-like environment right in the browser.

    Authors
    Developer, digital product enthusiast, tinkerer, sharer, open source lover