1

I want to be able to have the same function name for two implementations, depending on the type of the parameter (or the type of genericity given to the function).

The main goal behind this is to be able to have a deserialize method on a serializer to be able to deserialize both objects and arrays, instead of having deserialize and deserializeArray.

Here is an example of what I'd like to do:

export type Abstract<T = any> = Function & { prototype: T };
export type Instantiable<T = any> = new (...args: any[]) => T;
export type Class<T = any> = Abstract<T> | Instantiable<T>;

function deserialize<T>(obj: any, clazz: Class<T>): T{
    return obj as T;
}

function deserialize<T extends any[]>(obj: any[], clazz: Class<T>): T{
    let array:T = [];
    for (let data of obj) {
        array.push(data as T);
    }
    return array;
}

See it on typescript playground

But the problem is that I can't figure out how to create both signatures without getting a typescript error, also, I can't find out how to "give" the Class<T> of Foo[] since both Foo[] and Array<Foo> won't work.

N.B: implementation are just examples, it won't be implemented like that later on.

1 Answer 1

3

Javascript does not support overloading, which is why you can not use the same name for two different functions.
Typescript supports overloading only with signatures, that is, there's only one implementation but you declare more than one signature for this implementation.

In your case, something like this:

function deserialize<T>(obj: any, clazz: Class<T>): T;
function deserialize<T extends any[]>(obj: any[], clazz: Class<T>): T;
function deserialize<T>(obj: any, clazz: Class<T>): T {
    return obj as T;
}

(code in playground)

The actual implementation signature needs to match all of the other signatures, otherwise the compiler will complain.
You can read more about it here: Functions > Overloads

Sign up to request clarification or add additional context in comments.

2 Comments

Okay so I have to declare multiple signatures and filter on the type of obj by myself (array or not array)?
Exactly. It's not pretty, but that's due to the javascript restrictions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.