The announcement regarding the completion of `js-sys` project mentioned:
We explored using TypeScript for the frontend, but opted against it because TypeScript does not specify whether functions throw exceptions.
1) Is this statement accurate? 2) If not, are there methods to indicate if functions can throw in TypeScript? Can the compiler assist in this?
Below are two approaches. The first one doesn't perform actual type checking, but serves as a way to communicate intentions with other developers. The second method involves some runtime overhead and manual effort, but provides limited type checking.
// Unchecked solution
type OrThrow<T> = T;
function add(a: number, b: number): OrThrow<number> {
return a + b;
}
// Checked solution with runtime cost and manual work
type Exn<T> = T & { __canThrow: true };
function exn<T>(t: T): Exn<T> {
return t as Exn<T>;
}
function sum(a: number, b: number): Exn<number> {
return exn(a + b);
}