Skip to content

Instantly share code, notes, and snippets.

@ciiqr
Last active December 3, 2022 03:39
Show Gist options
  • Save ciiqr/6cce21b64f769e5c91deb38e80a2168e to your computer and use it in GitHub Desktop.
Save ciiqr/6cce21b64f769e5c91deb38e80a2168e to your computer and use it in GitHub Desktop.
Alternate solution to @ThePrimeagen's typescript problem in AOC day 2, 2022 stream
interface FooEvent {
ack: { ack: string };
bash: { bash: string };
bar: { bar: string };
buzz: { buzz: string };
}
interface BarEvent {
ack: { ack: string };
bash: { bash: string };
buzz: { buzz: string };
}
// as opposed to type guards, casting, or this shit: https://www.totaltypescript.com/tips/use-generics-to-dynamically-specify-the-number-and-type-of-arguments-to-functions
// when your types don't have a natural distriminator field imo the best option
// is to define a new type with a discriminator field and a field with your type
type TypeToEvent =
| {
type: "bar";
event: BarEvent;
}
| {
type: "foo";
event: FooEvent;
};
export function write({ type, event }: TypeToEvent) {
if (type === "foo") {
console.log(type, event.bar);
}
}
write({
type: "foo",
event: {
ack: { ack: "ack" },
bash: { bash: "bash" },
// bar: { bar: "bar" },
buzz: { buzz: "buzz" },
},
});
interface FooEvent {
ack: { ack: string };
bash: { bash: string };
bar: { bar: string };
buzz: { buzz: string };
}
interface BarEvent {
ack: { ack: string };
bash: { bash: string };
buzz: { buzz: string };
}
interface TypeToEvent {
foo: FooEvent;
bar: BarEvent;
}
export function write(
type: keyof TypeToEvent,
event: TypeToEvent[keyof TypeToEvent],
) {
if (type === "foo") {
console.log(type, event.bar);
}
}
write("foo", {
ack: { ack: "ack" },
bash: { bash: "bash" },
buzz: { buzz: "buzz" },
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment