Kipper icon indicating copy to clipboard operation
Kipper copied to clipboard

[Feature] Implement `cast as`, `try as` and `force as`

Open Luna-Klatzer opened this issue 7 months ago • 0 comments

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 of EXP does not match the type of T.
  • EXP force as T, which casts the value at runtime to T and if the type of EXP at runtime is invalid then a TypeError should be thrown.
  • EXP try as T, which casts the value at runtime to T and if the type of EXP at runtime is not matching then the expression will evaluate to null.

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 type any has a numeric (str) value and should be converted to a string (num), where the compatibility is unknown since for example if the any 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 return null if the conversion fails and avoids having to do a try...catch when using force as, but makes the result nullable. If successful, the expression evaluates to the original value of the expression but cast to a different type.

Luna-Klatzer avatar Jul 25 '24 08:07 Luna-Klatzer