I currently have two interfaces
, with one extending the other. However, I am looking for a way to extend the first interface
and make all of its types optional without having to duplicate all the definitions in the second interface
. This would eliminate the need for rewriting or redefining the initial interface
, which is also utilized elsewhere.
This is how it appears:
interface First {
type1: string
type2: string
}
// Redundant rewrite (why even extend?)
interface Second extends First {
type1?: string
type2?: string
type3: string
type4: string
}
// Desired extension approach (doesn't work as expected)
interface Second extends First? {
type3: string
type4: string
}
After conducting research, I stumbled upon this related question. Nonetheless, my dilemma is somewhat distinct as I aim to make the whole extended interface
optional instead of just certain types within it.
Is there any feasible way to achieve this in Typescript, or must I reconcile with creating a lengthy second interface
?
Update (clarifying reason behind desired functionality):
In developing a React web application, I have a component responsible for displaying data entities from my database, permitting users to modify any entity value. I want this React component to accommodate scenarios where users either create new entities or edit existing ones.
To elaborate on the scenario mentioned earlier, assume that the database entity's attributes align with the First interface
, while the React component relies on two props passed down following the structure of the Second interface
. The React component will always incorporate the two Second values, but not necessarily those from First.
If a user creates a new entity, I aim to set up the React component solely with Second values, avoiding the need to specify null values for every attribute in First. On the contrary, when editing an existing entity, I intend to pass both First and Second values.
Irrespective of the scenario, the UI remains consistent, albeit constructed with differing value sets.