Search code examples
reactjstypescriptnext.jstypescript-types

TypeScript React infer function argument from passed prop


I am trying to replace any type in the code below to something that will allow me to type the value of the onSelected function based on what type was passed as the value in the items array so I dont lose typesafety in the callback.

interface DropdownProps {
    items: {
        value: any;
        title: string;
    }[];
    defaultSelected?: number;
    onSelected: (value: DropdownProps["items"][number]["value"]) => void;
}

I tried adding <T> to DropdownProps, but then TS requires to provide something instead of T the component type.

interface DropdownProps<T> {
    items: {
        value: T;
        title: string;
    }[];
    defaultSelected?: number;
    onSelected: (value: DropdownProps<T>["items"][number]["value"]) => void;
}

export const Dropdown: React.FC<DropdownProps< here >> = (props) => { ... }

Solution

  • Setting the types as per @wonderflame 's comment gives typing on the type of value in the onSelected function

    interface DropdownProps<T> {
        items: {
            title: string;
            value: T;
        }[];
        defaultSelected?: number;
        onSelected: (value: DropdownProps<T>["items"][number]["value"]) => void;
    }
    
    export const Dropdown = <T,>(props: DropdownProps<T>) => { ... }