typescript - Bir tuple'a enum eklemek mümkün mü?
Bir üye olarak enum alan bir demet oluşturmak istiyorum.
enum Category {
Medieval,
Fantasy,
SciFi,
Pirates
}
let games: [string, string, boolean, enum] = [
{ name: 'Star Wars: Imperial Assault', company: 'Fantasy Flight', available: true, category: Category.SciFi },
{ name: 'Game of Thrones: Second Edition', company: 'Fantasy Flight', available: false, category: Category.Fantasy },
{ name: 'Merchans and Marauders', company: 'Z-Man Gaming', available: true, category: Category.Pirates },
{ name: 'Eclipse', company: 'lautapelit', available: false, category: Category.SciFi }
]
VisualStudio, demet içindeki enum değerinde bir hata döndürüyor
Beklenen tür
TypeScript oyun alanı bağlantısı
Cevap #1
Bunu dene
enum Category {
Medieval,
Fantasy,
SciFi,
Pirates
}
function getAllGames() {
let games: {name:string, company:string, available:boolean, category:Category}[] = [
{ name: 'Star Wars: Imperial Assault', company: 'Fantasy Flight', available: true, category: Category.SciFi },
{ name: 'Game of Thrones: Second Edition', company: 'Fantasy Flight', available: false, category: Category.Fantasy },
{ name: 'Merchans and Marauders', company: 'Z-Man Gaming', available: true, category: Category.Pirates },
{ name: 'Eclipse', company: 'lautapelit', available: false, category: Category.SciFi }
]
// de functie GetAllGames returned de let array 'games' zodat deze array ergens anders gebruikt kan worden.
return games;
}
Cevap #2
Bunu aslında bir demetle yapmak şöyle görünürdü...
enum Category {
Medieval,
Fantasy,
SciFi,
Pirates
}
let games: [string, string, boolean, Category][] = [
[ 'Star Wars: Imperial Assault', 'Fantasy Flight', true, Category.SciFi ],
[ 'Game of Thrones: Second Edition', 'Fantasy Flight', false, Category.Fantasy ],
[ 'Merchans and Marauders', 'Z-Man Gaming', true, Category.Pirates ],
[ 'Eclipse', 'lautapelit', false, Category.SciFi ]
];
Ayrıca, 'games'i tanımlamadan önce demet türünü çıkararak bunu biraz daha temiz hale getirebilirsiniz...
type Game = [string, string, boolean, Category];
ve sonra yaz
let games: Game[] = [
// Games go here
];
