¿Cómo extender una propiedad en una matriz de objetos en mecanografiado?
Tengo el siguiente código de reacción:
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;aquí
React.useEffect(() => { setListCustom([ { id: "3", newProperty: "new" //issue is here, how to extend List to have newProperty without modifying List? } ]); }, []); Tengo que establecer una nueva propiedad en List, pero no quiero modificar List porque está vinculado a AppProps. ¿Cómo puedo 'extenderlo' en la línea const [listCustom, setListCustom] = React.useState<List[]>([]); ?
No tiene sentido crear una List2 duplicada como
interface List2 { id: string; newProperty: string }Puede ampliar la interfaz de la lista:
interface List2 extends List { newProperty: string; }O puede usar un tipo de intersección:
type List2 = List & { newProperty: string }La interfaz no se puede hacer en línea, pero la intersección puede ser:
const [listCustom, setListCustom] = React.useState<(List & { newProperty: string })[]>([]);