use union type in onClick prop

Viewed 108

i'm using react and typescript i have a interface that i define my types in that.in this file i have a onClick prop.this accepted a function as value.my problem is how can i define function overloads for my onclick prop.eg:onClick:()=>void | (number)=>void ETC. this is my interface file.in other words i want my onClick prop like my color prop can accept union type.

import React from "react";

export interface IButtonText {
    children: React.ReactNode;
    leadingIcon: React.ReactNode;
    className: string;
    color: 'primary' | 'secondary';
    onClick: ()=>void;
}

2 Answers

Just missing parentheses:

export interface IButtonText {
    ...
    onClick: (() => void) | ((num: number) => void);
}

But this might be better choice:

export interface IButtonText {
    ...
    onClick: (num?: number) => void;
}

Union type produces an error


interface IButtonText {
    onClick: (() => void) | ((num: number) => void);
}


const foo = (props: IButtonText) => {
    props.onClick() // error, but should be ok
}

You are looking for intersection instead of union.

Intersection of function produces function overload.

Consider this example:



interface IButtonText {
    onClick: (() => void) & ((num: number) => void);
}


const foo = (props: IButtonText) => {
    props.onClick() // ok
    props.onClick(2) // ok

}

This approach onClick: (num?: number) => void; in this case is perfectly valid, but if you have more than two elements in a union it can be hard to write correct function type with optional arguments

Related