如何在打字稿中擴展物件陣列中的屬性?
我有以下反應代碼:
interface List {
id: string;
}
interface AppProps {
list: List[];
}
const App: React.FC<AppProps> = ({ list }) => {
const [listCustom, setListCustom] = React.useState<List[]>([]);
React.useEffect(() => {
setListCustom([
{
id: "3",
newProperty: "new" //issue is here, how to extend List to have newProperty without modifying List?
}
]);
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
};
export default App;
在這里
React.useEffect(() => {
setListCustom([
{
id: "3",
newProperty: "new" //issue is here, how to extend List to have newProperty without modifying List?
}
]);
}, []);
我必須將新屬性設定為 List,但我不想修改 List,因為它與 AppProps 相關聯。我怎樣才能在線“擴展”它 const [listCustom, setListCustom] = React.useState<List[]>([]);?
List2創建一個重復的like是沒有意義的
interface List2 {
id: string;
newProperty: string
}
uj5u.com熱心網友回復:
您可以擴展串列介面:
interface List2 extends List {
newProperty: string;
}
或者您可以使用交叉點型別:
type List2 = List & { newProperty: string }
介面不能行內,但交集可以是:
const [listCustom, setListCustom] = React.useState<(List & { newProperty: string })[]>([]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/481029.html
標籤:javascript 反应 打字稿
上一篇:Typescript這個推斷型別無法獲取父超類的型別
下一篇:隨機化陣列中的專案并保持原始順序
