Overloads on Arrow Functions

  Kiến thức lập trình

I have:

type OnCloseType = {
  (gesture: 'close-button' | 'cancel' | 'escape'): void;
  (gesture: 'confirm', value: string): void;
  (gesture: string, value?: string): void;
};

const onClose: OnCloseType = (gesture, value) => {
    if (gesture === "confirm") {
        value // <= 'value' is possibly 'undefined'.
    } else {
        value
    }
}

I expect that value type can’t ve undefined in the first if block. How can fix that?

Also I tried:

function onClose(gesture: 'close-button' | 'cancel' | 'escape'): void;
function onClose(gesture: 'confirm', value: string): void;
function onClose(gesture: string, value?: string): void {
    if (gesture === "confirm") {
        value // <= 'value' is possibly 'undefined'.
    } else {
        value
    }
}

It didn’t work also.

LEAVE A COMMENT