Declaring multiple arguments configurations of a function in typescript

I have a function that can accept one parameter and it can have multiple types.

    getItems(user: User | null = null) {
        if (user instanceof User) return getItemsOfUser(user);
        getAllItems();
    }

In order to increase readability I wonder if it is possible to have a notation like this one:

    getItems(user: null)
    getItems(user: User) {
        if (user instanceof User) return getItemsOfUser(user);
        getAllItems();
    }

The logic in this layer is supposed to receive a generic case and call the more specific service functions.

>Solution :

Yes, you are seeking function overload
See : how-to-overload-functions

Leave a Reply