簡體   English   中英

確保 Typescript 數組具有特定值

[英]Ensure a Typescript array has a specific value

我正在構建一個下拉式組件,值和選項是不同的道具。 我希望使用 Typescript 來確保該值是一個有效選項。 雖然我可以在運行時執行此檢查,但我覺得這是我應該能夠在 TS 中執行的操作。

這可能嗎?

interface Props<N extends number> {
    count: N,
    options: Array<N | number> // Tuples don't work here, since this can be any length
}

const Component = <N extends number>({count, options} : Props<N>) => {
  // We could do a runtime check to verify that `count` is in `options`, but I'd rather do the check earlier if possible
}

Component({count: 5, options: [1,2,3]}) // This should be an error

這個想法是將countoptions的文字類型都推斷為通用類型NO 這對於N是微不足道的,但對於O我們需要提示編譯器推斷數字文字的元組類型,而不僅僅是number[] 我們可以通過將O包裝成一個看起來像[...O]可變元組類型來實現這一點。

為了實現驗證,我們可以使用條件類型來檢查N是否是O[number]的成員。 如果它不是成員,則條件解析為never導致錯誤,因為不能將任何內容分配給never

interface Props<N extends number, O extends readonly number[]> {
  count: N;
  options: N extends O[number] ? readonly [...O] : never;
}
const Component = <N extends number, O extends readonly number[]>({
  count,
  options,
}: Props<N, O>) => {};

只要作為options傳遞的數組是元組類型,這就可以正常工作。

Component({ count: 5, options: [1, 2, 3] }); // error

Component({ count: 5, options: [1, 2, 3, 5] }); // ok

Component({ count: 5, options: [] as number[] }); 
// ok, all the elements in options are number and 5 does extend number :/

如果options是一個數組類型,它的元素是number類型,並且5確實擴展了number最終通過了類型檢查。


操場

暫無
暫無

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

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