1

Is it possible to pass a TypeScript type as a prop to a React Component?

export type ActivitiesType = {
  RUN: "RUN";
  WALK: "REST";
  ROUNDS: "ROUNDS";
};

<MyComponent activity={ActivitiesType.RUN} />

Then in MyComponent:

const MyComponent = ({ activity }) => {
  if(activity === ActivitiesType.RUN) {
    // Do something
  }
}
4
  • I'm not sure if it's possible as types aren't there at runtime. Why not using a field type in activity? Here is more from the official doc Commented Apr 7, 2020 at 12:17
  • 4
    Why not use Enums? Commented Apr 7, 2020 at 12:19
  • You are looking for generics, please read this stackoverflow.com/questions/57208569/… maybe is a duplicate Commented Apr 7, 2020 at 12:22
  • 1
    Related: How do the different enum variants work in TypeScript?. Your type is essentially an ambient enum. You need a real one that exists at runtime. Commented Apr 7, 2020 at 12:23

1 Answer 1

1

Ritaj was right, Enums can do this:

enum ActivitiesType {
  RUN: "RUN";
  WALK: "REST";
  ROUNDS: "ROUNDS";
}

type Props = {
  type: ActivitiesType;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.