簡體   English   中英

React Typescript不可分配給type參數

[英]React typescript is not assignable to parameter of type

我在反應項目中使用打字稿。

我收到以下錯誤。

類型'{團隊:{主頁:{名稱:字符串; }; 離開:{名稱:字符串; }; } []'不能分配給'Fixtures [] |類型的參數。 (()=>燈具[])'。

我的類型定義和在react組件中的用法如下。

type Team = {
    name: 'Liverpool' | 'Man Utd';
};

type Fixtures = {
    teams: {
        home: {
            name: Team;
        },
        away: {
            name: Team;
        },
        winner: Team;
    };
};

const initialFixtures = [
    {
        teams: {
            home: {
                name: 'Liverpool',
            },
            away: {
                name: 'Man Utd',
            },
        },
        winner: 'Liverpool',
    },
];

然后我在我的React組件中使用它,如下所示,但是

// Error is in `initial fixtures`
const [fixtures, updateFixtures] = useState<Fixtures[]>(initialFixtures);

誰能看到我在做什么錯? 當我說這是一個Team時,我看不到它在哪里推斷它是一個字符串。

問題與反應無關,與Typescript如何推斷字符串文字類型有關。 除非有理由,否則Typescript不會推斷字符串文字類型。

在這種情況下, initialFixtures是無類型的。 因此,打字稿沒有理由將name推斷為'Liverpool' | 'Man Utd' 'Liverpool' | 'Man Utd'因此將其推斷為string 當您稍后嘗試將其推斷類型的initialFixtures分配給Fixture[] ,分配失敗(因為無法將string分配給Team ):

type Team =  'Liverpool' | 'Man Utd';

type Fixtures = {
    teams: {
        home: {
            name: Team;
        },
        away: {
            name: Team;
        },
    };
    winner: Team;
};

const initialFixtures= [
    {
        teams: {
            home: {
                name: 'Liverpool',
            },
            away: {
                name: 'Man Utd',
            },
        },
        winner: 'Liverpool',
    },
];
let o: Fixtures[] = initialFixtures; // error here 
// Type '{ teams: { home: { name: string; }; away: { name: string; }; }; winner: string; }[]' is not assignable to type 'Fixtures[]'.

簡單的解決方案是鍵入initialFixtures ,而不要求編譯器推斷任何內容,而只是檢查對象文字):

const initialFixtures: Fixtures[]= [
    {
        teams: {
            home: {
                name: 'Liverpool',
            },
            away: {
                name: 'Man Utd',
            },
        },
        winner: 'Liverpool',
    },
];
let o: Fixtures[] = initialFixtures; //ok

一方面,您的數據形狀不匹配:

請注意,在initialFixtures數組中使用的是'term'而不是'away',然后是'away'而不是'name'。 因此,您的形狀不匹配。 將您的initialFixtures常量聲明為Fixtures []可能會有所幫助,因為打字稿可能不會隱式意識到這一點。

看起來useState是一個多態函數,它采用分配了Fixtures類型的數組或返回Fixtures []類型的回調。

據我所知:

term: {
  away: 'Man Utd',
}, 

應該

away: {
  name: 'Man Utd'
}

type Team = 'Liverpool' | 'Man Utd';

原因是打字稿認為您的結構應為:

            home: {
                name: {
                   name: 'Liverpool'
                }
            },
            away: {
                name: {
                   name: 'Man Utd'
                }
            },

另外,您可以保持團隊類型不變,但將燈具類型更改為:

type Fixtures = {
    teams: {
        home: Team;
        away: Team;
        winner: Team;
    };
};

請記住,獲勝者將是{name:'Teamname'}的對象,而不是團隊名稱的字符串

暫無
暫無

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

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