Answer the question
In order to leave comments, you need to log in
Is it possible to make dynamic interfaces?
Does the language support something similar?
// 1 компонент
interface AnimalProps {
name: string;
}
const Animal: FC<AnimalProps> = (props) => {
return <span>{props.name}</span>;
};
// 2 компонент
interface PersonProps {
age: number;
}
const Person: FC<PersonProps> = (props) => {
return <span>{props.age}</span>;
};
// затем какой-то другой компонент, который должен возвращать
// какой-то другой компонент в зависимости от переданного типа,
// и в зависимости от типа, который будет передан
// определялись бы дополнительные наборы
interface ComponentProps {
type: 'animal' | 'person';
// smth that depends on type
// ...
...({
'animal': AnimalProps,
'person': PersonProps,
}[this.type]),
}
const Component: FC<ComponentProps> = (props) => {
switch (props.type) {
case 'animal':
return <Animal name={props.name} />;
case 'person':
return <Person age={props.age} />;
}
};
const Usage: FC<ComponentProps> = (props) => {
// write type then get support
return <Component type="animal" />;
};
Answer the question
In order to leave comments, you need to log in
gist example :
enum What {
animal,
person
}
type AnimalProps = {
what: What.animal;
name: string;
};
type PersonProps = {
what: What.person;
age: number;
};
type ComponentProps = AnimalProps | PersonProps;
interface AnimalProps {
name: string;
}
interface PersonProps {
age: number;
}
type ComponentProps =
| ({ type: 'animal'; } & AnimalProps)
| ({ type: 'person'; } & PersonProps)
// or
interface AnimalType extends AnimalProps {
type: 'animal';
}
interface PersonType extends PersonProps {
type: 'person';
}
type ComponentProps2 = AnimalType | PersonType;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question