Provide type hints to monaco editor

て烟熏妆下的殇ゞ 提交于 2019-12-04 15:26:06

As of Monaco version 0.90, since https://github.com/Microsoft/monaco-editor/issues/203 has been fixed, you can add achieve this partially if you use JSDoc in the editing code.

For this code in the left side of the Monaco playgound:

    // validation settings
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
    noSemanticValidation: true,
    noSyntaxValidation: false
});

// compiler options
monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
    target: monaco.languages.typescript.ScriptTarget.ES6,
    allowNonTsExtensions: true,
    allowJs: true
});

// extra libraries
monaco.languages.typescript.javascriptDefaults.addExtraLib([
    'declare class SomeEventType {',
    '    /**',
    '     * Heres the doco for someProperty',
    '     */',
    '    someProperty: string',
    '}',
].join('\n'), 'filename/facts.d.ts');

var jsCode = [
    '"use strict";',
    '',
    "/**",
    " * @param {SomeEventType} event",
    " */",
    "function onMyEvent(event) {",
    "",
    "}"
].join('\n');

monaco.editor.create(document.getElementById("container"), {
    value: jsCode,
    language: "javascript"
});

Means that the editor can now interpret the event parameter as a SomeEventType:

This is how we do it for magikcraft.io: drop this code straight into the left pane in the playground, then hit Run:

monaco.editor.create(document.getElementById("container"), {
    value: "function hello() {\n\talert('Hello world!');\n}",
    language: "typescript"
});

const fact = `declare namespace custom { export function onMyEvent(event: customClass): void; 

export class customClass { 
    customProperty: string;
}`;
const factFilename = 'myCustomNamespace';
this.monaco.languages.typescript.typescriptDefaults.addExtraLib(fact, factFilename);

Now, in the right pane, then type: custom. and you'll get autocomplete for the custom facts.

Put this in the editor in the Monaco Playground:

monaco.editor.create(document.getElementById("container"), {
    value: "function hello() {\n\talert('Hello world!');\n}",
    language: "typescript"
});

const fact = `declare function onMyEvent(event: string): void; 
`;
const factFilename = 'myCustomNamespace1';
this.monaco.languages.typescript.typescriptDefaults.addExtraLib(fact, factFilename);

Now when you type onMyEvent in the right-hand pane, you'll get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!