簡體   English   中英

打字稿中對象數組的聯合?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM