簡體   English   中英

TypeScript:使用擴展運算符指定該值必須在數組中

[英]TypeScript: Specify that value must be in Array using spread operator

我正在嘗試定義一種類型,其中 favoriteFruit 屬性的值必須是選項數組中的一個項目。 選項數組是動態/未知的(無法使用聯合類型“|”)。

const options = ["apple", "orange", "kiwi"]; // Dynamic list that can be modified in the future 

type Person =  {
  name: string;
  favoriteFruit: /* --- val in [...options] --- */
};

const personA:Person = {name: "Jack", favoriteFruit: "apple"}; // OK
const personB:Person = {name: "John", favoriteFruit: "orange"}; // OK
const personC:Person = {name: "Jane", favoriteFruit: "banana"}; // ERROR

我發現了這個: 如何將字符串數組轉換為 typescript 類型? .

const arr = ["foo", "bar", "loo"] as const

type arrTyp = typeof arr[number]; // "foo" | "bar" | "loo"

我希望這就是你要找的

[更新]

const options = ["apple", "orange", "kiwi"] as const; // Dynamic list that can be modified in the future 
type optionsType = typeof options[number];

type Person =  {
  name: string;
  favoriteFruit: optionsType;/* --- val in [...options] --- */
};

const personA:Person = {name: "Jack", favoriteFruit: "apple"}; // OK
const personB:Person = {name: "John", favoriteFruit: "orange"}; // OK
const personC:Person = {name: "Jane", favoriteFruit: "banana"}; // ERROR
console.log(personC)

你可以保持你的選項列表動態

你可以在這里測試

暫無
暫無

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

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