簡體   English   中英

具有強類型屬性的自定義類型的假設

[英]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);

是錯誤的。

當傳入的PetDognewPet._type只能是"dog" ,新的pet將被添加到myPetMap["dog"] ,這是一個Dog對象的數組。

當傳入的PetFishnewPet._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.

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