Guide on correctly importing the Monaco IStandaloneCodeEditor interface in Vue3 using the Composition API

While working with Monaco, I came across a challenge in defining the instance type for encapsulating a component package. I am unsure about how to import the interface IStandaloneCodeEditor | IStandaloneDiffEditor, or if it is necessary at all.

<script lang="ts">
import * as monaco from "monaco-editor";
props: {
  diffEditor: {
      type: Boolean,
      default: false,
  },
  codes: {
    type: String,
    default: () => {
      return "";
    },
  },
  oldCodes: {
    type: String,
    default: () => {
      return "";
    },
  },
  language: {
    type: String,
    default: () => {
      return "json";
    },
  },
  readOnly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  theme: {
    type: String,
    default: () => {
      return "vs";
    },
  },
}
setup(props: any) {
  const state = reactive({
    editorInstance: {}   // **Questioning how to define the type of editorInstance - IStandaloneCodeEditor or IStandaloneDiffEditor seem appropriate but importing them correctly remains uncertain**
  });

  onMounted(() => {
    if (props.diffEditor) {
      state.editorInstance = monaco.editor.createDiffEditor(props.containerRef, {
        value: props.codes,
        readOnly: props.readOnly,
        theme: props.theme, 
        ...props.editorOptions,
      });
      
      // **Attempting to assign type any to state.editorInstance does not yield the desired outcome** 
      (<any>state.editorInstance)!.setModel({
        original: monaco.editor.createModel(props.oldCodes, props.language),
        modified: monaco.editor.createModel(props.codes, props.language),
      });
    } else {
      state.editorInstance = monaco.editor.create(props.containerRef, {
        value: props.codes,
        language: props.language,
        readOnly: props.readOnly,
        theme: props.theme, 
        ...props.editorOptions,
      });
    }
  })

  const getModifiedEditor = () => {
    // Attempting to assign type any to state.editorInstance does not work 
    return props.diffEditor ? (<any>state.editorInstance)!.getModifiedEditor() : state.editorInstance;  
    };

  const getOriginalEditor = () => {
    return props.diffEditor ? (<any>state.editorInstance)!.getOriginalEditor() : state.editorInstance;
  };
}

I believe that introducing the interface is the correct approach.

I came across this information in "monaco-editor/esm/vs/editor/editor.api.d.ts"

export interface IStandaloneCodeEditor extends ICodeEditor {
    updateOptions(newOptions: IEditorOptions & IGlobalEditorOptions): void;
    addCommand(keybinding: number, handler: ICommandHandler, context?: string): string | null;
    createContextKey<T>(key: string, defaultValue: T): IContextKey<T>;
    addAction(descriptor: IActionDescriptor): IDisposable;
}

export interface IStandaloneDiffEditor extends IDiffEditor {
    addCommand(keybinding: number, handler: ICommandHandler, context?: string): string | null;
    createContextKey<T>(key: string, defaultValue: T): IContextKey<T>;
    addAction(descriptor: IActionDescriptor): IDisposable;
    getOriginalEditor(): IStandaloneCodeEditor;
    getModifiedEditor(): IStandaloneCodeEditor;
}

and I imported them like so

import {IStandaloneDiffEditor,IStandaloneCodeEditor} from "monaco-editor/esm/vs/editor/editor.api";

error:

TS2305: Module '"../../node_modules/monaco-editor/esm/vs/editor/editor.api"' has no exported member 'IStandaloneDiffEditor'.

Answer №1

using monaco from 'monaco-editor';

let myMonacoEditor: monaco.editor.IStandaloneCodeEditor;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting problem with TypeScript observables in Angular 5

Having trouble with a messaging app, specifically an error related to TS. The syntax checker in the Editor is flagging this issue: Type 'Observable<{}>' is not compatible with type 'Observable'. Type '{}' cannot be as ...

Struggling to navigate through rows in a Material UI Table

After performing a search in my TextField, the rows appear correctly in the console. However, the table itself does not update at all. I attempted to set the result of the search to a new array, but this made my TextField read-only. Any assistance with fur ...

Delay the execution until all promises inside the for loop are resolved in Angular 7 using Typescript

I am currently working on a project using Angular 7. I have a function that contains a promise which saves the result in an array as shown below: appendImage(item){ this.imageCompress.compressFile(item, 50, 50).then( result => { this.compressedI ...

The currentRoute variable appears to be displaying a route value that is inconsistent with the value being displayed

Having trouble retrieving the current route of a component with router.currentRoute displaying unexpected behavior. router.currentRoute shows the intended route /admin: RefImpl {__v_isShallow: true, dep: undefined, __v_isRef: true, _rawValue: {…}, _valu ...

Receiving a null value when accessing process.env[serviceBus]

Currently, I am focusing on the backend side of a project. In my environment, there are multiple service bus URLs that I need to access dynamically. This is how my environment setup looks like: SB1 = 'Endpoint=link1' SB2 = 'Endpoint=link2&a ...

Error message in Typescript: "Property cannot be assigned to because it is immutable, despite not being designated as read-only"

Here is the code snippet I am working with: type SetupProps = { defaults: string; } export class Setup extends React.Component<SetupProps, SetupState> { constructor(props: any) { super(props); this.props.defaults = "Whatever ...

Dealing with various node types in a parse tree using TypeScript: Tips and Tricks

I am in the process of converting my lexer and parser to TypeScript. You can find the current JavaScript-only code here. To simplify, I have created an example pseudocode: type X = { type: string } type A = X & { list: Array<A | B | C> } ty ...

Storing prop object in LocalStorage when clicking on a Vue3 component

I am currently attempting to pass a prop (faction) from a Component called Faction Option when the @click event for the option occurs. FactionOption.vue <script setup> import { selectFaction } from '../../composables/selectFaction'; def ...

Can you guide me on how to specify the return type in NestJS for the Session User in a request?

async authenticated(@Req() request: Request) { const user = request.user return user } It is important for the 'user' variable to have the correct type globally. While working with express passport, I came across the following: decl ...

Formik: Customizing form rendering based on sibling form values

<ParentComponent> ... <Formik initialValues={getInitialValues(data)} enableReinitialize={true} validationSchema={schema} isInitialValid={!isNew} onSubmit={() => {}} render={formikProps => ( <SimulatorForm&g ...

The health check URL is experiencing issues: Unable to locate any routes

I am currently developing a .net Core 2.2/Angular 8 application and recently came across the HealthCheck feature. I decided to incorporate it into my application, so here is a snippet from my Startup.cs file: using HealthChecks.UI.Client; using Mi ...

Parsing JSON results in the return of two objects

I am analyzing a JSON file, expecting it to return Message[] using a promise. This code is similar to the one utilized in the Heroes sample project found in HTTP documentation { "data": [ {"id":"1","commid":"0","subject":"test1subject","body":" ...

The React application, when built using `npm run build`, experiences difficulty loading image sources after deployment to App Engine

In my React frontend application, I have the logo.png file being loaded in Header.tsx as an img element like this: <img className={classes.headerLogo} src={'logo.png'} alt={"MY_LOGO"}/> The directory structure looks lik ...

Showcase data objects in JSX format

I have an Object stored in my state that looks like this: console.log(state) I've developed a component to display a card for each item within this object (which contains sub-objects). Despite trying multiple approaches, I keep encountering an error ...

Images appear as plain text in the preview of VUE 3 (with TypeScript)

Currently, I am developing a Portfolio website and have encountered an issue. While everything runs smoothly with npm run dev, the problem arises when I use npm run preview. In this scenario, some of the images within the files named 3dModellingFiles.ts do ...

Expanding MaterialUi styled components by incorporating TableCellProps: A guide

When trying to create a styled TableCell component in a separate file, I encountered an error in TypeScript (ts(2322)). TypeScript was indicating that the properties "component," "scope," and "colSpan" could not be used because they do not exist in StyledC ...

Tips for managing Typescript Generics while utilizing the styled function provided by the '@mui/material/styles' package

import Table,{TableProps} from 'my/table/path' const StyledTable = styled(Table)({ ...my styles }) const CustomTable = <T, H>(props: TableProps<T, H>) => { return <StyledTable {...props} /> } This is the issue I encoun ...

The RxJs Observer connected to a websocket only triggers for a single subscriber

Currently, I am encapsulating a websocket within an RxJS observable in the following manner: this.wsObserver = Observable.create(observer=>{ this.websocket.onmessage = (evt) => { console.info("ws.onmessage: " + evt); ...

Angular's forEach function seems to be stuck and not loop

I'm attempting to cycle through a list of objects in my Angular/Typescript code, but it's not working as expected. Here is the code snippet: businessList: RemoteDataSet<BusinessModel>; businessModel: BusinessModel; this.businessList.forE ...

Can TypeScript provide a method for verifying infinite levels of nested arrays within a type?

Check out this example The concept behind this is having a type that can either be a single object or an array of objects. type SingleOrArray<T> = T | T[]; The structure in question looks like this: const area: ItemArea = [ { name: 'test1& ...