[英]union for array of object in typescript?
How to extends an property in array of object in typescript?如何在打字稿中扩展对象数组中的属性?
I have below react code:我有以下反应代码:
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;
In here在这里
React.useEffect(() => {
setListCustom([
{
id: "3",
newProperty: "new" //issue is here, how to extend List to have newProperty without modifying List?
}
]);
}, []);
I have to set new property to List, but I don't want to modify List because it's tied to the AppProps.我必须将新属性设置为 List,但我不想修改 List,因为它与 AppProps 相关联。 How can I 'extends' it in line
const [listCustom, setListCustom] = React.useState<List[]>([]);
我如何在
const [listCustom, setListCustom] = React.useState<List[]>([]);
行中“扩展”它? ?
It doesn't make sense to create a duplicated List2
like创建一个重复的
List2
是没有意义的
interface List2 {
id: string;
newProperty: string
}
You can either extend the list interface:您可以扩展列表接口:
interface List2 extends List {
newProperty: string;
}
Or you can use an intersection type:或者您可以使用交叉点类型:
type List2 = List & { newProperty: string }
The interface can't be done inline, but the intersection can be:接口不能内联,但交集可以是:
const [listCustom, setListCustom] = React.useState<(List & { newProperty: string })[]>([]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.