microsoft / microsoft/TypeScript

Proposal: Operator overloading and primitive type declarations

Open
#42,218 11 comments 26 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Suggestion

🔍 Search Terms

Operators, operator types, operator overloading

✅ Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Introduce a way to show what types can/cannot be gained from using an operator on a value of a type.

No, I am not asking for operations to be replaced with functions or such, like many other issues have asked for, I am merely asking for a way to show what types that an operation will yield when performed between two types.

Currently, there is no way to describe operator types in TS.

📃 Motivating Example

I don't have an idea for the syntax, but I'll introduce a partial syntax to showcase the idea here.

Let's imagine that TS allowed us to declare primitive types via, say, a primitive keyword:

primitive string {
    +(lhs: string, rhs: string) => string;
    +=(lhs: string, rhs: string) => string;
}

primitive symbol {
    +(lhs: symbol, rhs: never) => never;
}

primitive number {
    +(lhs: number, rhs: number) => number;
    -(lhs: number, rhs: number) => number;

    +(lhs: number, rhs: string) => string;
}

This is already valid TS:

let x: string = 2 + "";
let y: number = 2 + 2;

This suggests that TS already has the notion of overloaded operators that I have suggested.

Note that operators may never have a body, as TSC is not allowed to emit runtime code for the operations.

Now, TS doesn't presently allow us to declare primitives, but operations between objects always throw the error:

Operator '{op}' cannot be applied to types '{object}' and '{object}'.

And generally, yes, that is a good thing, but is it always?
Take this example:

const result: string = new String("foo") + new String("bar");

I know that the ES abstract ToPrimitive will be called on both of these objects, resulting in the primitive string value contained within.
Run the code yourself, it will result in "foobar", and we know this, so let's tell TSC that too!
But, instead of the type string being the result of the concatenation operator, we get this:

Operator '+' cannot be applied to types 'String' and 'String'.

Let's say that we were using a type that becomes a number, ex: WebAssembly.Global:

const options = {
    value: "i32",
    mutable: false
};
const x = WebAssembly.Global(options, 100);
const y = WebAssembly.Global(options, 1);

const z: number = x + y; // 101

That string example could could now be something like this:

class Str extends String {
    +(lhs: Str, rhs: Str) => string; // just an operation, and it's types

    // !(lhs: Str) { return !this; } // I'm not proposing runtime operations, that is out of scope for TS!
}

const result: string = new Str("foo") + new Str("bar"); // no error: return type is "string" primitive!

Of course, as with anything else, this can be misused, but it's no worse than the already existing 2 + "" semantics.

💻 Use Cases

This can likely solve issues such as https://github.com/microsoft/TypeScript/issues/28682 solely via user-implemented types!

If we could declare opaque types, such as those mentioned in https://github.com/microsoft/TypeScript/issues/15408 or https://github.com/microsoft/TypeScript/issues/40075, one could do stuff like, say, creating a NaN type, and stricter number types, all without runtime overhead and erasable types.

Toss in throw types and we can get some good error messages out of it too:

primitive NaN {
    +(lhs: NaN, rhs: number) => throw `One of the operands is possibly NaN, this arithmetic may be unsafe`
}

primitive strict_number {
    /(lhs: strict_number, rhs: strict_number) => strict_number;
    /(lhs: strict_number, rhs: 0) => NaN; // could be 'never' or throw
    **(lhs: strict_number, rhs: strict_number) => NaN | strict_number;
}

declare function isNaN(n: number): n is NaN;

let x: strict_number = 42;
let y: strict_number = x / 0; // Error type 'NaN' is not assignable to 'strict_number'

let a = x ** x;

if ( !isNaN(a) ) {
    // ... use a like normal number
} else {
    // oh no!
}

Another use, working with pointers into, say, WebAssembly memory, it usually makes no sense to do something like raising it to an exponent, and this could allow us to scope what operations are permitted.
Before:

// wasm_func(): number
// wasm_func2(n: number): void
const index: number = wasm_func();
wasm_func2(index ** 3);

after:

primitive pointer /*extends number?*/ {
    +(lhs: Pointer, rhs: number) => pointer;
    -(lhs: Pointer, rhs: number) => pointer;

    +(lhs: Pointer, rhs: pointer) => number;
    -(lhs: Pointer, rhs: pointer) => number;
}
// wasm_func(): pointer
// wasm_func2(n: pointer): void
const index: pointer = wasm_func();
wasm_func2(index ** 3); // TS error: operation "**" cannot be performed between types "pointer" and "number"

There will have to be some TSC enforced rules in order for it to actually be useful, ex: the return type of + must extend number | string | bigint, because nothing else could be possible.

If the primitive type idea is too radical, it could be completely decoupled from the operator overloading, so that I may perform my object arithmetic with the safety of TS. :)


Also, eventually, TS may have to implement this anyways: https://github.com/tc39/proposal-operator-overloading

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no source file, test, or concrete implementation entry point. Start by reviewing TypeScript's existing operator checking and the linked TC39 operator-overloading proposal; completion would require an agreed design, implementation scope, and tests for the proposed semantics.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.