Created
August 17, 2023 08:46
-
-
Save okayurisotto/7239728ed785bab124a58078bb9a09d5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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