1
1
1thater2021-12-11 18:17:26
typescript
1thater, 2021-12-11 18:17:26

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

3 answer(s)
A
Alexander, 2021-12-11
@1thater

https://codesandbox.io/s/qna-q-1087328-3cmq3

A
Alexandroppolus, 2021-12-11
@Alexandroppolus


gist example :

enum What {
    animal,
    person
}

type AnimalProps = {
    what: What.animal;
    name: string;
};

type PersonProps = {
    what: What.person;
    age: number;
};

type ComponentProps = AnimalProps | PersonProps;

W
WbICHA, 2021-12-11
@WblCHA

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;

https://www.typescriptlang.org/play?#code/JYOwLgpg...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question