Is there a way in React to change a prop type to avoid TypeErrors?

I’m wondering if there’s a way to change a prop type if the one that is being passed isn’t of the type expected.

For example, if my component expects to receive an object (Using PropTypes or using TypeScript notation), but an array is passed, that array should be converted into an object (It can be an empty object).

Is there a way to archive this?

5 thoughts on “Is there a way in React to change a prop type to avoid TypeErrors?”

  1. You may want to use a generic type. Documented as:

    A major part of software engineering is building components that not only have well-defined and consistent APIs, but are also reusable. Components that are capable of working on the data of today as well as the data of tomorrow will give you the most flexible capabilities for building up large software systems.

    In languages like C# and Java, one of the main tools in the toolbox for creating reusable components is generics, that is, being able to create a component that can work over a variety of types rather than a single one. This allows users to consume these components and use their own types.

    You can then convert to the desired type:

    const convert2Array = <T>(prop: T): T[] => {
        let arr: T[];
        if (Array.isArray(prop)) {
            arr = prop;
        } else if (typeof prop === 'object' && prop !== null) {
            arr = Object.values(prop);
        } else {
            arr = [prop];
        } 
    
        return arr;
    };
    
    convert2Array('str'); // ['str']
    convert2Array(7); // [7]
    convert2Array(['an', 'existing', 'array']); // ['an', 'existing', 'array']
    convert2Array({foo: 'bar', zip: 'zap'}); // ['bar', 'zap']
    
    Reply

Leave a Comment