Home > Back-end >  Is it possible to define a functional component with a specific type?
Is it possible to define a functional component with a specific type?

Time:07-01

I have a functional component that can work with different kinds of model structures.

Lets assume that the model can be TMODEL.

See below some code to explain the situation:

interface MyCompProps {
    model: TMODEL,
    records?: TMODEL[],
    // other stuff...
}

const MyComp = (props: MyCompProps) => {
    // component code comes here...
    // this component code needs TMODEL to be used in various ways

    // like for e.g. see below

    const [record, setRecord] = useState<TMODEL>(props.model);

    const load() {
        // load data from ajax
        const data = loadAjax('model-specific-endpoint...');

        // build record from model and set state
        setRecord(new TMODEL(data));
    }

    // in the render, it may also be useable...

    return (
        <React.Fragment>
        ...
            Record ID: {record.id}
        ...
        </React.Fragment>
    );
};

Also if I am able to define the TMODEL in above code, I guess this is how how I could be able to use it:

    // some component code...

    const cat = new CatModel(...);

    // some component code...

    return (
        ...

        <MyComp model={cat} />

        ...
    );
    // some component code...

Is there such a way to achieve that? Or is there a better approach to make a component a type specific?

CodePudding user response:

You can use class implementations in order to force consumer of your component to abide by type rules for certain props.

For example, you can have something like this:

abstract class Model {
   abstract prop1: string;
   abstract prop2: string;
   abstract prop3: number;
}

interface IMyGenericComponentProps {
   model: Model;
   // ... and some other props
}

Then, in your outer component when you want to consume this generic component, you can define any custom class but it is required to implement abstract class. For example:

class CatModel implements Model {
// Here you will need to make sure that you implemented everything that is imposed by abstract Model
}

const cat = new CatModel(...);

return <MyGenericComponent model={cat} /> // and this will work because cat implements everything from abstract class
  • Related