Skip to content

Instantly share code, notes, and snippets.

@okayurisotto
Created August 17, 2023 08:46
Show Gist options
  • Save okayurisotto/7239728ed785bab124a58078bb9a09d5 to your computer and use it in GitHub Desktop.
Save okayurisotto/7239728ed785bab124a58078bb9a09d5 to your computer and use it in GitHub Desktop.
type Item = StringItem | NumberIntem;
type StringItem = { key: "string"; value: string };
type NumberIntem = { key: "number"; value: number };
type ObjectUnionToEntryUnion<T extends Item> = T extends unknown
? [T["key"], T["value"]]
: never;
type Entry = ObjectUnionToEntryUnion<Item>;
const items: Item[] = [
{ key: "number", value: 1 },
{ key: "string", value: "hey" },
];
// ERROR
{
const entries = items.map<Entry>((item) => {
return [item.key, item.value];
});
}
// OK
// `key`の種類が増えたらその分`case`を書く羽目になる?
{
const entries = items.map<Entry>((item) => {
switch (item.key) {
case "string":
return [item.key, item.value];
case "number":
return [item.key, item.value];
default:
return item satisfies never;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment