-
-
Notifications
You must be signed in to change notification settings - Fork 666
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support custom type casts #678
Comments
Maybe we could hijack Object.prototype.valueOf, but make it generic? Something like class MyClass {
valueOf<T>(): T {
// statically evaluate `T` and convert `this` -> `T`
return converted;
}
} Might even be possible to implement it in a way that if it does not have a generic parameter, it defaults to |
I like this. Also need somehow determine implicit & explicit conversion. For example: class MyClass {
// implicit conversion
valueOf<T>(): T {
...
}
// explicit conversion like `new MyClass() as f64`
as<T>(): T {
...
}
} |
Another variant: class MyClass {
// implicit conversion
@operator.implicit("as")
as<T>(): T { // or valueOf<T>()
...
}
// explicit conversion
@operator.explicit("as")
as_expl<T>(): T {
...
}
} |
Explicit casting is most interesting feature for math related packages. For example I want to overload linear operators ("+") and ("*") for complex numbers algebra or vector space. //z3 = z1 * z2;
@operator("*")
static add(a: Complex, b: Complex) {
return new Complex(a.re + b.re, a.im + b.im);
} This operators also should works for constants and we need to create explicit casting or 2 operator overloading //z2 = c * z1;
@explicit @operator.postfix("as")
as_expl<f64>(): Complex {
return new Complex(this, 0);
}
//another way
@polymorphism @operator("*")
static mul(c: f64, z: Complex) { // left
return new Complex(c * z.re, c * z.im);
}
@polymorphism @operator("*")
static mul(z: Complex, c: f64) { // right
return new Complex(c * z.re, c * z.im);
} This can be the most yummy part of AS and I think we shouldn't stay with TS superset strictness. |
I think we should stay as compatible with TS as possible. The further away we go, the more difficult it becomes to make AS code compile to plain JS not just Wasm, less interoperable, and less compatible with TS tooling. People could of course choose not to use incompatible features, but maybe there is some library that someone wrote only for AS, and the consumer wants to use it in their compile-to-JS pipeline; if that lib has more incompatible features, the more work it is to port. I would love to see AS get closer, than further. |
It would be nice to support custom type cast. As an example, see MaxGraey/as-bignum#19
The text was updated successfully, but these errors were encountered: