-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Description
Feature Proposal
Modern JavaScript and Typescript syntax allows easy support for type operators, similar to that in C++, when a property of certain type can be implied whenever the type is needed.
By analogy with C++, I suggest to add word operator, to be treated the same as get, but to be also used for the type resolution.
Example:
class A {
}
class B {
private prop1: A;
private value: number;
operator name1(): A {
return this.prop1;
}
operator name2(): number {
return this.value;
}
}Using operators:
function test1(obj: A) {
}
function test2(val: number) {
}
const obj = new B;
test1(obj); // translated into test1(obj.name1)
test2(obj); // translated into test2(obj.name2)
// we can use those as regular get operators also:
const a: A = obj.name1;
const b: number = obj.name2;TypeScript would treat operator in the same way as get, i.e. by simply replacing operator with get, while allowing automatic resolution of type by redirecting to the right get method.
Also, during the type parsing, TypeScript will detect and report any case where the type resolution is ambiguous, which should be fairly easy. For example, if a class implements an operator with the same return type more than once, this is a definitive type ambiguity.
Another example of type ambiguity to be reported as error would be when multiple types are supported at the same time:
class A {
}
class B {
private prop1: A;
operator name1() : number {
}
}
// TEST:
function test(val: B | number) {
}
const obj = new B();
// the following line should throw a type ambiguity error,
// because it cannot choose which to pass in - the object or its property name1:
test(obj);
- This could be implemented without emitting different JS based on the types of the expressions
There only would a replacement of operator with get, nothing else.
- This isn't a runtime feature (e.g. library functionality, **non-ECMAScript syntax with JavaScript
We only substitute an object with object+property, and that's it.