Enhance TypeScript functionality with operator overloading

I am currently involved in a project that heavily relies on vector and matrix mathematics, and I am keen on incorporating operator overloading into my code.

Although there are Babel plugins available (such as https://github.com/rob-blackbourn/jetblack-operator-overloading) that enable operator overloading for JavaScript, they do not seem to work seamlessly with TypeScript, especially when it comes to the TS language server for VS Code. While there are workarounds involving the use of // @ts-ignore, I personally find this approach unappealing as it undermines the benefits of type checking for the subsequent line of code.

My goal is to transform code like this (where a, b, and c represent custom objects):

a + b * c

Into something along the lines of:

a.__add__(b.__mul__(c))

In case, for instance, c is incompatible with the function __mul__, I would like VS Code to highlight either the original line or ideally the symbol c itself.

I envision the ability to preprocess the code before submitting it to the TS compiler (similar to what the Babel plugin accomplishes). However, I anticipate that VS Code would consistently flag an error (

Operator '+' cannot be applied to types 'Custom' and 'Custom'
).

My inquiry is as follows: Is there an existing project that delivers the aforementioned functionality? If not, is it feasible to enhance TypeScript and/or the TypeScript language server in this manner? Kindly share any relevant resources for further exploration.

Furthermore, I am intrigued by how JSX (utilized in React) seamlessly integrates with TS using a unique syntax. Are there any other projects that alter TS in a similar fashion?

Answer №1

Babel is specific to processing JavaScript code, which means that if you want to utilize it with TypeScript, you'll need to create a custom TypeScript transformer and configure it with ts-loader. However, a potential issue might arise when the ForkTsCheckerWebpackPlugin checks the syntax of your code, in which case you may have to disable this plugin.

Below is a code snippet demonstrating how to create a basic transformer:

export function createTransformer (): ts.TransformerFactory<ts.SourceFile> {
  console.log("Hello, I am a newly created transformer");
  return (context: ts.TransformationContext) => {
    return (sourceFile: ts.SourceFile) => {
      function visit (node: ts.Node): ts.Node {
      return ts.visitNode(sourceFile, visit)
    }
  }
}
export default createTransformer

Furthermore, you'll need to make adjustments to your project configuration. For instance, if you are using Vue, your vue.config.js file could look like this:

const PipeTransformer = require('./pipe-transformer').default

module.exports = {
  // .... other configurations 
  chainWebpack: config => {
    // The ts-pipe-operator plugin cannot be used with Babel, as Babel only processes JavaScript files.
    config.module.rule('ts').use('ts-loader').tap(options => {
      options.transpileOnly = true
      options.appendTsSuffixTo = ['\\.vue$']
      options.happyPackMode = false
      options.getCustomTransformers = () => ({
        before: [PipeTransformer()]
      })
      return options
    })
  }
}

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

One creative method for iterating through an array of objects and making modifications

Is there a more efficient way to achieve the same outcome? Brief Description: routes = [ { name: 'vehicle', activated: true}, { name: 'userassignment', activated: true}, { name: 'relations', activated: true}, { name: &apos ...

Creating an array of reusable components in Vue 3 with Typescript - How can I pass it into another component?

I have developed a customizable Button component that can be styled dynamically and accept values for text/icons, etc. Here is the code for my "ActionButton" in Vue 3. Although I am new to this framework, I am facing some difficulties understanding certai ...

Is there a way to order the execution of two functions that each produce promises?

With my code, I first check the status of word.statusId to see if it's dirty. If it is, I update the word and then proceed to update wordForms. If it's clean, I simply update wordForms. I'm looking for advice on whether this is the correct a ...

Identifying Classifications Based on Input Parameters

I'm encountering some difficulty in typing a function that calls an external API and returns data based on the parameters sent. Here is what I have so far... import axios from 'axios'; interface IGetContactArgs { properties?: string[]; } ...

Enhancing view with Typescript progressions

My current view only displays a loader.gif and a message to the user. I am looking to enhance the user experience by adding a progress indicator, such as "Processing 1 of 50", during the data update process. The ts class interacts with a data service layer ...

Determine whether there is greater available space above or below a specific element within the DOM

I'm looking to create a dynamic layout where an input field is accompanied by a list in a div, positioned either above or below depending on available space. This setup needs to account for the fact that the input field could be located anywhere on th ...

What are the steps to create a circular progress bar in an Ionic 3 application?

Can anyone help me create a circular progress bar in Ionic 3? I'm new to Ionic and have already attempted to install the jQuery circle progress package by running npm install jquery-circle-progress. The installation was successful, but now I'm un ...

how can JavaScript be used to retrieve an object based on a condition from an array of objects and an ArrayList

My JavaScript challenge involves working with an array of objects called arrobj and a list called prgList. The goal is to extract the names from arrobj based on the programs listed in prgList. If the program exists in arrobj, it should be displayed accor ...

Retrieve the values of a dynamic JSON object and convert them into a comma-separated string using Typescript

I recently encountered a dynamic JSON object: { "SMSPhone": [ "SMS Phone Number is not valid" ], "VoicePhone": [ "Voice Phone Number is not valid" ] } My goal is to extract the va ...

Using Typescript Classes in a NodeJS Environment

Trying to work with Data Classes in NodeJs that were defined in Typescript has led me to question if there is a simpler approach. Previously, in JavaScript, I could easily create an instance of a class like this: let myBuilding = new Building And then a ...

The @Input directive is not compatible with the OnPush change detection strategy

page.html <app-parcel-delivery-cost-promo [parcelDeliveryCost]="parcelDeliveryCost"> </app-parcel-delivery-cost-promo> page.ts changeDetection: ChangeDetectionStrategy.OnPush, parcelDeliveryCost: Partial<ParcelDeliveryCostModel>; ...

Error: The nested property of the dynamic type cannot be indexed

Within my coding project, I've devised an interface that includes various dynamic keys for API routes, along with the corresponding method and response structure. interface ApiRoutes { "auth/login": { POST: { response: { ...

When the value of a react state is used as the true value in a ternary operator in Types

Attempting to implement sorting on a table is resulting in the following error: (property) direction?: "asc" | "desc" No overload matches this call. Overload 1 of 3, '(props: { href: string; } & { active?: boolean; direction? ...

Ways to fix: Unable to locate package 'xlsx'

I'm encountering an issue with the xlsx package in my UI5 project (using TypeScript) as it is unable to find the module. Can someone please help me with resolving this problem? Here is how I am importing it in my main.controller.ts file: import { XLS ...

Tips for showing data from an hour ago in Angular

Here is the code snippet provided: data = [ { 'name' : 'sample' 'date' : '2020-02-18 13:50:01' }, { 'name' : 'sample' 'date' : '2020-02- ...

What could be causing the TypeScript type error within this Effector effect subscriber?

Working on a front-end application utilizing React, Typescript, Effector, FetchAPI, and other technologies. Created an Effector effect to delete an item in the backend: export const deleteItemFX = createEffect({ handler: (id: string) => { return ...

What is the best way to programmatically download a file in Angular 4 without explicitly specifying the file name?

Below is the code snippet: importedSaveAs(blob, 'somefile.txt'); I'm currently facing an issue with hard-coding the file name in the above code. I would like to make it dynamic based on the response header. However, I'm unable to acc ...

How can a TypeScript object be declared with a single value assignment to itself?

Whenever I try to declare an object and assign a key to itself, I encounter errors. I have attempted different methods, but the error persists. const a = { d:123, a:a//<-TS2448: Block-scoped variable 'a' used before its declaration. } co ...

What is the best way to combine properties from Type1 and Type2 to create a new type in Typescript?

Here is a snippet of code I'm working with: interface Notification { message: TemplatedEmail & Email, //current attempt which doesnt do what I want } interface Destination { ccAddresses?: string[], bccAddresses?: string[], toAddresses: st ...

Issue during Docker build: npm WARN EBADENGINE Detected unsupported engine version

Currently, I am constructing an image based on mcr.microsoft.com/devcontainers/python:0-3.11-bullseye. In my docker file, I have included the following commands towards the end: RUN apt-get update && apt-get install -y nodejs npm RUN npm install np ...