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. How can I 'extends' it in line const [listCustom, setListCustom] = React.useState<List[]>([]);
?
It doesn't make sense to create a duplicated List2
like
interface List2 {
id: string;
newProperty: string
}
CodePudding user response:
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 })[]>([]);