Is there a way to retrieve a JSON object representing a Typescript object from the Monaco Editor?

Issue: I am in need of assistance to convert a typescript model that utilizes intellisense from extraLibs (an option in the monaco editor) into a JSON object. This JSON object will then be sent to an API for processing.

Here is the code snippet that you can paste into the Monaco Editor Playground for further testing

// extra libraries
monaco.languages.typescript.typescriptDefaults.addExtraLib('enum Types {type1 = 1,type2 = 2} interface Page {name: string;type: Types;}', 'ts:filename/facts.d.ts');

var jsCode = `
// This is a typescript model that users can modify in the monaco editor
var model: Page = {
    name: "Page",
    type: Types.type1
}

// I require the above typescript model in JSON format to send it to an API as illustrated below
/*
{
    "name": "Page",
    "type": 1
}
 */
`;

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

// Exploring some functionality
monaco.languages.typescript.getTypeScriptWorker().then(x => {
    x('').then(y => {
        y.getEmitOutput('hello').then(z => {
            console.log(z)
        });
    })
})

Important Note: I am currently working with Angular

Answer №1

To retrieve the last text in the editor, you can utilize the getValue() function. After obtaining the text, it is necessary to employ the typescript compiler services API to transpile it into JavaScript code.

Illustrative Example:

const jsCode = `var model: Page = {
    name: "Page",
    type: Types.type1
}
`

const container = document.getElementById('container');

require.config({ paths: { 'vs': 'https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f8959796999b97d59d9c918c978ab8c8d6c0d6cb">[email protected]</a>/min/vs' }});
window.MonacoEnvironment = { getWorkerUrl: () => proxy };

let proxy = URL.createObjectURL(new Blob([`
self.MonacoEnvironment = {
baseUrl: 'https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="79141617181a16541c1d100d7cecaee2cecc1">[email protected]</a>/min/'
};
importScripts('https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bf6f4f5faf8f4b6fefff2eff4e9dbabb5a3b5a8">[email protected]</a>/min/vs/base/worker/workerMain.js');
`], { type: 'text/javascript' }));

require(["vs/editor/editor.main"], async function () {

const libCode = `enum Types {
type1 = 1,
type2 = 2
}

interface Page {
name: string;
type: Types;
}`

monaco.languages.typescript.typescriptDefaults.addExtraLib(libCode, 'ts:filename/facts.d.ts');

let editor = monaco.editor.create(container, {
value: jsCode,
language: 'typescript',
theme: 'vs-dark' 
});

const result = window.ts.transpileModule(libCode + editor.getValue(), { compilerOptions: { module: window.ts.ModuleKind.CommonJS }});
console.log(result);

});
html, body, #container {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35585a5b54565a1850515c415a4775051b07051b05">[email protected]</a>/min/vs/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typescript/3.9.3/typescript.js"></script>
<div id="container"></div>

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

Build encountered an error: module exported a null value unexpectedly

Encountering an error message while running the Angular Build (ng build --prod): ERROR in: Unexpected value 'null' exported by the module 'SharedModule' @NgModule({ declarations: [InputComponent, InputSimpleComponent, ModelEditComp ...

Fade in the new list item

In my TS file, there is a dynamic rendering of a list to the template: <ul *ngFor="let product of products let ind = index" > <li> <span> This is where the text will appear</span> < ...

Understanding the concept of inconsistent return points in Typescript: What implications does it carry?

I am currently working on converting a NodeJs JavaScript code to TypeScript. The code snippet below shows how I save uploaded files using JavaScript and now I'm encountering an error when trying to do the same in TypeScript. The error message says "Fu ...

Improving DOM rendering speed in Internet Explorer 11 with Angular 2

Looking for tips on how to boost performance for an Angular 2 app specifically on Internet Explorer 11? Our website runs smoothly on Chrome and Firefox, but experiences slow DOM rendering on IE 11. While I know the browser engine plays a part in this slug ...

What steps should I follow to set up a TypeScript project that incorporates JavaScript modules compiled from PureScript?

TL;DR I am looking to develop TypeScript typings for compiled PureScript modules and include them in my npm package. I am willing to manually maintain these typings, but I am struggling with the configuration needed in tsconfig.json (up and downstream) and ...

Generating JSON data with Ruby for a collection of items

I'm a beginner with Ruby. My goal is to generate a JSON file for a set of elements. To achieve this, I am utilizing the each function to fetch the data. The desired structure of the JSON file for a 4 element array is as follows: '{ "desc" ...

Removing duplicate entries from a list of dictionary elements extracted from Twitter json data

I've successfully downloaded Twitter Users' objects, Here's an example of one object { "id": 6253282, "id_str": "6253282", "name": "Twitter API", "screen_name": &qu ...

Using ngOnChange on a FormGroup in Angular

Is there a way to detect real-time changes in the fields of a FormGroup? My component structure consists of a simple parent-child setup: Parent Component View <my-child [myForm]="myForm"></my-child> Child Component Controller @Input() myFor ...

Guide on finding a JSON object using a name obtained from another object in jq

Here is an example of a JSON structure: { "categories": { "category1": { "info": "data1" }, "category2": { "info": "data2" } }, "selected_category": "category2" } I want to retrieve the ...

API for making cURL requests on Android devices

As a newcomer to programming in Android, I am looking to retrieve JSON data from the website for integration into my Android app. How can I successfully request this data in JSON format using curl -X GET --header 'Accept: application/json' --hea ...

What is the best way to extract targeted information from a json/jsonp response?

I received a JSON response from a Weather API. My goal is to extract specific data related to a property, and here is the response: { "response": { "version": "0.1", "termsofService": "http://www.wunderground.com/weather/api/d/terms.h ...

Encountered an issue when trying to update information in mongodb

Error: The document with _id ObjectId('5a02f5aac293238265959fd7') has been updated, causing the (immutable) field '_id' to be changed to _id: ObjectId('5a02f7cdc0d5868391967dd5') {_id: ObjectId('5a02f5aac293238265959fd7 ...

Leverage JSON data to generate individual elements, rows, and columns for every object within the array

Just starting out with JavaScript and struggling a bit. We need to fetch data from this URL: and then manipulate the data to create new rows (tr) and columns (td) for each game without altering the HTML file. The desired outcome should resemble this: http ...

Exploring the World of ES6 Modules, VueJS, and TypeScript

In my pursuit of creating a simplistic setup, I aim to incorporate the features mentioned above. In the realm of JavaScript code, below snippet plays a crucial role: <script type="module" src="./myapp.js"></script> This script is responsible ...

Utilizing NGXS operators to modify state and then storing the updated data in Firebase

I have a class for updating a user with an action type: export class Update { public static readonly type = '[Users] Update'; constructor(public readonly id: string, public readonly changes: Partial<User>) {} } Below is the action ...

Converting a JSON String into a Map

Recently, I have come across a JSON value that looks like the example below and I am looking for advice on how to efficiently parse and extract the pair values of data from it, especially in Java using the org.json library. { "columns" : [ "Book", " ...

When the NativeScript ScrollView component is initialized, it automatically scrolls to a specific section

I included a ScrollView in my component as shown below: <ScrollView height="108" orientation="horizontal" sdkToggleNavButton> . . . some content </ScrollView> The scroll width is approximately 120 ...

Exploring the creation of a streamlined resource locking system in TypeScript - quick demo with a test scenario attached

I am faced with a challenge on my server where I receive concurrent requests, but certain R/W resources cannot be accessed simultaneously. Implementing locks at the database level is not practical for me, so I am looking to create a function that can turn ...

Exploring the power of indexing in @for loop within HTML in Angular 18

Is it possible to define the index variable in @for loop in Angular 17? const users = [ { id: 1, name: 'Ali' }, { id: 2, name: 'reza' }, { id: 3, name: 'jack' }, ]; <ul> @for (user of users; track user.i ...

Is it recommended to utilize optionals for attributes of object models that are to be extracted from JSON data?

In my iOS app, the standard setup involves making HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed into Swift objects. Originally, I classified properties as either required or optional based on the databas ...