[英]Assumption of Type in Custom Type with Strongly-Typed Properties
考慮以下Typescript類型......
export type Dog = {
color: string,
earsFloppy: boolean,
_type: "dog"
}
export type Fish = {
color: string,
finsFlowy: boolean,
_type: "fish"
}
export type Pet = Dog | Fish;
export type PetMap = {
dog: Dog[],
fish: Fish[]
}
考慮以下函數(也在Typescript中)......
var myPetMap = { dog: [], fish: [] };
function addToPetMap(newPet: Pet): void {
myPetMap[newPet._type].push(newPet);
}
我的項目中有一個幾乎相同的設置,但是我收到以下錯誤:
[ts] Cannot invoke an expression whose type lacks a call signature. Type '((...items: Dog[]) => number) | ((...items: Fish[]) => number)' has no compatible call signatures. [2349]
但是,執行以下操作可以解決問題......
var myPetMap = { dog: [], fish: [] };
function addToPetMap(newPet: Pet): void {
switch(newPet._type) {
case 'dog':
myPetMap[newPet._type].push(newPet);
break;
case 'fish':
myPetMap[newPet._type].push(newPet);
break;
}
}
就好像myPetMap[newPet._type].push(newPet)
存在的范圍內必須知道newPet._type
的值或具體。 它不能存在於newPet._type
的值不能保證為dog
(x)或fish
。
但是,因為Dog._type
的類型是"dog"
而Fish._type
的類型是"fish"
,所以Dog._type
的值只能是"dog"
而Fish._type
的值只能是"fish"
。 我不明白為什么
myPetMap[newPet._type].push(newPet);
是錯誤的。
當傳入的Pet
是Dog
, newPet._type
只能是"dog"
,新的pet將被添加到myPetMap["dog"]
,這是一個Dog
對象的數組。
當傳入的Pet
是Fish
, newPet._type
只能是"fish"
,新的寵物將被添加到myPetMap["fish"]
,這是一個Fish
對象數組。
因為Pet
可能是兩種類型的_type
屬性的類型是固定值,所以我看不出任何類型不匹配問題,其中Dog
被添加到Fish
數組,反之亦然。 newPet._type
的值不需要具體或已知,以便將其添加到正確的數組中。
有沒有辦法解決? 任何Typescript編譯器選項或不同的編寫方式?
編輯:
newPet._type
的類型是string
。
這是我一度想到的,但是嘗試更改newPet._type
的值newPet._type
產生自己的錯誤......
newPet._type = "Something Else";
[ts] Type '"Something Else"' is not assignable to type '"dog" | "fish"'. [2322]
(property) _type: "dog" | "fish"
您的方法沒有任何問題,但您確實遇到了類型系統的限制。 打字稿不能跟隨變量之間的關系,因此打字稿無法區分你的函數和這個函數之間的區別:
function addToPetMap(_type: "dog" | "fish", newPet: Pet): void {
myPetMap[_type].push(newPet);
}
在上面的例子中,可以傳入'dog'
和Fish
的實例。 雖然在你的情況下這是不可能的,因為_type
來自newPet
,編譯器不能遵循這個,它只是將newPet._type
的類型視為"dog" | "fish"
"dog" | "fish"
並引發錯誤。
您使用交換機的解決方法是非常安全的方法。 類型斷言也是合適的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.