简体   繁体   中英

Pass a TypeScript Type as a prop to a React component?

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
  }
}

Ritaj was right, Enums can do this:

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

type Props = {
  type: ActivitiesType;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM