簡體   English   中英

確保數組具有聯合中的所有類型

[英]Make sure array has all types from a union

假設我有一個看起來像這樣的工會

type Colors = 'red' | 'blue' | 'pink'

是否可以根據此聯合對數組進行類型檢查並確保該數組包含所有類型?

IE:

const colors: UnionToTuple<Colors> = ['red', 'blue']  // type error, missing 'pink'
const colors: UnionToTuple<Colors> = ['red', 'blue', 'pink']  // no error

這個答案中汲取靈感,您可以創建一個函數,通過使用傳遞數組的類型參數 T 進行類型檢查。將其鍵入為T extends Colors[]以確保數組的每個項目都在Colors ,並鍵入它作為[Colors] extends [T[number]] ? unknown : 'Invalid' [Colors] extends [T[number]] ? unknown : 'Invalid'以確保顏色類型的每個項目都在傳遞的數組中:

type Colors = 'red' | 'blue' | 'pink';
const arrayOfAllColors = <T extends Colors[]>(
  array: T & ([Colors] extends [T[number]] ? unknown : 'Invalid')
) => array;

const missingColors = arrayOfAllColors(['red', 'blue']); // error
const goodColors = arrayOfAllColors(['red', 'blue', 'pink']); // compiles
const extraColors = arrayOfAllColors(['red', 'blue', 'pink', 'bad']); // error

更一般地,將它包裝在另一個函數中,以便您可以傳遞和使用聯合類型的類型參數:

type Colors = 'red' | 'blue' | 'pink';
const arrayOfAll = <T>() => <U extends T[]>(
  array: U & ([T] extends [U[number]] ? unknown : 'Invalid')
) => array;
const arrayOfAllColors = arrayOfAll<Colors>();

const missingColors = arrayOfAllColors(['red', 'blue']); // error
const goodColors = arrayOfAllColors(['red', 'blue', 'pink']); // compiles
const extraColors = arrayOfAllColors(['red', 'blue', 'pink', 'bad']); // error

擴展 CertainPerformances 答案,對於廣義的 function 你可以寫一個工廠

type Colors = 'red' | 'blue' | 'pink';

const enforceArrayMembers =
    <T>() =>
    <U extends T[]>(
        array: U & ([T] extends [U[number]] ? unknown : 'Invalid'),
    ) =>
        array;

const arrayOfAllColors = enforceArrayMembers<Colors>();
const missingColors = arrayOfAllColors(['red', 'blue']); // error
const goodColors = arrayOfAllColors(['red', 'blue', 'pink']); // compiles
const extraColors = arrayOfAllColors(['red', 'blue', 'pink', 'bad']); // error

// as IFEE
const missingColors2 = enforceArrayMembers<Colors>()(['red', 'blue']); // error
const goodColors2 = enforceArrayMembers<Colors>()(['red', 'blue', 'pink']); // compiles
const extraColors2 = enforceArrayMembers<Colors>()(['red', 'blue', 'pink', 'bad']); // error

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM