javascript - TypeScript: Angiv, at værdien skal være i Array ved hjælp af spread-operator


Jeg forsøger at definere en type, hvor værdien af egenskaben favoriteFruit skal være et element i options-arrayet. Hvor options-arrayet er dynamisk/ukendt (hvilket gør det umuligt at bruge unionstyper "|").

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

Svar #1

Jeg håber, dette er, hvad du leder efter

[OPDATERET]

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)

du kan holde din liste over muligheder dynamisk

Du kan teste her

Svar #2

Jeg fandt dette: Hvordan konverterer man et array af strenge til TypeScript-typer?

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

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

Relaterede artikler