简体   繁体   中英

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. 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
}

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 })[]>([]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM