![](/img/trans.png)
[英]Typescript for in loop, iterate through union type of object or array
[英]union for array of object in typescript?
如何在打字稿中擴展對象數組中的屬性?
我有以下反應代碼:
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
是沒有意義的
interface List2 {
id: string;
newProperty: string
}
您可以擴展列表接口:
interface List2 extends List {
newProperty: string;
}
或者您可以使用交叉點類型:
type List2 = List & { newProperty: string }
接口不能內聯,但交集可以是:
const [listCustom, setListCustom] = React.useState<(List & { newProperty: string })[]>([]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.