我有 3 種不同型別的專案,我有介面
interface TypeA{
name: string;
}
interface TypeB{
count: number;
}
interface TypeC{
date: Date;
}
此專案應呈現在專案串列中(在串列中,所有專案都來自同一型別)。根據專案的型別,呼叫不同的方法,這將呈現不同的布局。
export const ListItem: React.FC<ListItemProps> = (props) => {
let item = null;
switch (props.type) {
case "A":
item = renderTypeA(props);
break;
case "B":
item = renderTypeB(props);
break;
case "C":
item = renderTypeC(props);
break;
}
return item;
};
該方法應該只接受來自所需型別的專案。
const renderTypeA = (props: TypeAProps) => {
{...}
};
問題是我無法讓 Typescript 識別型別的所有屬性,也只能自動完成相應的型別。
我也嘗試過使用聯合型別“ListItemTypes”,
type ListItemTypes = TypeA | TypeB | TypeC
export const ListItem: React.FC<ListItemTypes> = (props) => {
...
};
但是當我嘗試包含 ListItem 時,我總是收到屬性丟失的錯誤。
<ListItem {...item /> <--- is telling me that properties are missing
有誰知道我該如何解決這個問題?
例子
uj5u.com熱心網友回復:
這是一個有區別的聯合使用的最小示例:
interface TypeA {
type: "A";
name: string;
}
interface TypeB {
type:"B";
count: number;
}
export const ListItem = (props: TypeA | TypeB) => {
let item = null;
switch (props.type) {
case "A":
item = renderTypeA(props); // TS know this must be TypeA in this block
break;
case "B":
item = renderTypeB(props);
break;
}
return item;
};
const renderTypeA = (props: TypeA) => {
props.name; // No error
};
const renderTypeB = (props: TypeB) => {
props.name; // Error
};
// Update:
const renderItem = () => {
const sampleData: Array<ListItemTypes> = [
{
type: "A",
count: 12, // This doesn't follow your ListItemTypes shape
},
];
// ListItem requires an object, not a list of objects
return sampleData.map(sd => <ListItem {...sd} />);
};
uj5u.com熱心網友回復:
我檢查了你的代碼,它拋出了錯誤,因為你正在將一個陣列解構到你的組件中。在您的代碼中
const renderItem = () => {
const sampleData = [
{
type: "A",
count: 12,
},
];
// incorrectly destructuring sampleData here
return <ListItem {...sampleData} />;
};
您應該能夠通過以下方式實作預期結果:
const renderItemA = () => {
const sampleData = {
type: "A" as const, // notice const assertion here
name: "name"
};
return <ListItem {...sampleData} />;
};
因為您定義type為文字型別,所以您需要const 斷言,以便
不應該擴大該運算式中的文字型別(例如,不要從“hello”變為字串)
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/419750.html
標籤:
上一篇:兩級通用嵌套和Parameters<T>會導致TypeScript錯誤。但是一級有效,沒有Parameter<T>有效。為什么?
