Sorry, but can you please try to be more specific when asking questions on the forum? It's meant for lengthy discussions or big posts, for small questions we have real-time chats.
So what exactly did you mean by a TypeScript-like library?
So I would like to do something like this
type TimingEvent = { name: "start"; userStarted: boolean } | { name: "closed"; duration: number };
const handleEvent = (event: TimingEvent) => {
switch (event.name) {
case "start":
const initiatedByUser = event.userStarted;
break;
case "closed":
const timespan = event.duration;
break;
}
};
type APIResponses = { version: 0; msg: string } | { version: 1; message: string; status: number } | { error: string };
const handleResponse = (response: APIResponses) => {
if ("error" in response) {
console.error(response.error);
return;
}
if (response.version === 0) {
console.log(response.msg);
} else if (response.version === 1) {
console.log(response.status, response.message);
}
};
You can also do functions that handle multiple types too:
proc foo(bar: Fizz | Buzz) =
echo bar.name
Assuming Fizz and Buzz both have a name field. You can also use when with is checks to do different pieces of code for the types too.