Di TypeScript, bagaimana cara mengonversi semua tipe dalam Union menjadi array dari tipe tersebut


Misalkan saya memiliki yang berikut ini:

type UnionType = CustomType1 | CustomType2 | CustomType3;

// is there a way to accomplish this, without having to type it out like so.
type UnionTypeArr = CustomType1[] | CustomType2[] | CustomType3[];

Jawaban #1

Anda dapat menggunakan tipe kondisional distributif (tipe kondisional berbentuk T extends X ? Y : Z di mana T adalah parameter tipe generik) untuk memisahkan sebuah union menjadi anggotanya, melakukan transformasi pada setiap anggota, dan menggabungkan hasilnya menjadi union lain:

type DistribArrayify<T> = T extends unknown ? Array<T> : never;

type UnionType = CustomType1 | CustomType2 | CustomType3;

type UnionTypeArr = DistribArrayify<UnionType>;
// type UnionTypeArr = CustomType1[] | CustomType2[] | CustomType3[]

Tautan playground ke kode