Kipper
Kipper copied to clipboard
[Feature] Implement `cast as`, `try as` and `force as`
Is there an existing proposal for this?
- [X] I have searched the existing issues
This feature does not exist in the latest version
- [X] I am using the latest version
Proposal
For easier and more intuitive type-checking, the user should be able to use one of the following casts to ensure the type of a variable:
-
EXP cast as T
, which simply casts the value and is checked at compile time, meaning it will always fail if the type ofEXP
does not match the type ofT
. -
EXP force as T
, which casts the value at runtime toT
and if the type ofEXP
at runtime is invalid then aTypeError
should be thrown. -
EXP try as T
, which casts the value at runtime toT
and if the type ofEXP
at runtime is not matching then the expression will evaluate tonull
.
Example:
var x: num = "2" cast as num; // fails at compile-time
...
var y: num = fetch(...) force as num; // known at runtime
...
var z: num | null = fun(...) try as num; // known at runtime
Exact behaviour / changes you want
- [ ] Implementation of the
EXP cast as T
/<T>EXP
conversion operator, which will be typed-checked at compile-time and works like a regular cast, like in TypeScript. It does not change the content of the expression and simply returns the value cast to a different type. If the type checker knows the cast is impossible, an error will be thrown at compile-time. - [ ] Implementation of the
EXP force as T
/<force T>EXP
conversion operator, which forces a conversion from one type to another, but will do runtime checks to see if the conversion is valid and works, and throw a runtime error if it failed. This for example could be used if a variable of typeany
has a numeric (str
) value and should be converted to a string (num
), where the compatibility is unknown since for example if theany
variable is an object, converting to a number would be false. If successful, the expression evaluates to the original value of the expression but cast to a different type. - [ ] Implementation of the
EXP try as T
/<try T>EXP
conversion operator, which tries a conversion from one type to another, but will do runtime checks to see if the conversion is valid and works. This will returnnull
if the conversion fails and avoids having to do atry...catch
when usingforce as
, but makes the result nullable. If successful, the expression evaluates to the original value of the expression but cast to a different type.