1
1
1thater2022-01-28 09:36:43
typescript
1thater, 2022-01-28 09:36:43

Is it possible, and how if so, to write a dynamic interface for React props to have a single key?

There are 2 different interfaces.

interface Name {
  name: string;
}

interface LastName {
  lastName: number;
}


And the family property.

If it is not provided.

Then the component should expect a set of props from Name.
<Component 
  name="Ivan" 
  lastName=""  // error lastName is not presented on type Name
/>


If provided, then the component should expect a set of props from LastName.
<Component 
  name="Ivan"  // error name is not presented on type LastName
  lastName="Fenia" 
  family={['Ivan', 'Anya']}
/>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexandroppolus, 2022-01-28
@1thater

interface Name {
    name: string;
}

interface LastName {
    lastName: string;
    family: string[];
}

function Component(props: Name): React.ReactElement;
function Component(props: LastName): React.ReactElement;
function Component(props: Name | LastName): React.ReactElement {
    if ('family' in props) {
        return <b>{props.lastName}</b>
    } else {
        return <b>{props.name}</b>
    }
}

S
Sergey Suntsev, 2022-01-28
@GreyCrew

What is the problem with combining them?

interface Name {
  name?: string;
  lastName?: number;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question