Home > Software design >  Typescript React How to Prepare Component to Expect Different Types
Typescript React How to Prepare Component to Expect Different Types

Time:04-19

I'm fetching some data from an API that looks like this:

features: [
  {
    featureId: '1',
    featureName: 'Damage feature 1',
    featureType: 'STRING',
  },
  {
    featureId: '2',
    featureName: 'Damage feature 2',
    featureType: 'DATETIME',
  },
  {
    featureId: '3',
    featureName: 'Damage feature 3',
    featureType: 'INTEGER',
  },
],

They are of different types, as you can see, they can be an integer, a string, a datetime, many different kinds, and I'm mapping them in a component like this:

interface CategoryFeatureProps {
  feature: string;
}

export const CategoryFeature = ({ feature }: CategoryFeatureProps) => {
  return (
    <p>{feature}</p>
  );
};

I'd like to know the correct way in Typescript to prepare the component to expect these different types in the interface.

CodePudding user response:

You'd need to update your CategoryFeatureProps to the following based on what you've currently got:

interface CategoryFeatureProps {
  feature: {
    featureId: string;
    featureName: string;
    featureType: string | number | Date;
  }
}

If you really wanted to break it up a bit more you could also do this:

type FeatureType = string | number | Date;

interface Feature {
  featureId: string;
  featureName: string;
  featureType: FeatureType;
}

interface CategoryFeatureProps {
  feature: Feature;
}

Additional Note:

export const CategoryFeature = ({ feature }: CategoryFeatureProps) => {
  return (
    <p>{feature}</p>
  );
}

This won't work because you can't render an object in React like this, rather just do something like this for now to test it all out:

export const CategoryFeature = ({ feature }: CategoryFeatureProps) => {
  return (
    <p>{JSON.stringify(feature)}</p>
  );
}

Now you'll safely render a string version of the object.

  • Related