0

I came across this code snippet on the Typescript namespaces page.

[snippet1]

export interface Selectors {
    select: {
      (selector: string): Selection;
      (element: EventTarget): Selection;
    };
}

I understand that the particular example is regarding an external library implemented in Javascript, and this declaration makes the library known to the Typescript compiler. Let's ignore the external library for the moment. If I were to write a class that implements the Selectors interface, what would that class look like?

Specifically, what does select in the code snippet signify - is it an overloaded method with 2 possible signatures? If I wrote it as shown below, would it mean the same? Then why write it as snippet1 above? 🤔

[snippet2]

export interface Selectors {
    select (selectorOrElement: string | EventTarget): Selection;
}

1 Answer 1

2

is it an overloaded method with 2 possible signatures?

Yes

If I wrote it as shown below, would it mean the same?

Yes, but your method has 2 drawbacks:

  • When using intellisense, the argument is now less precise. selector: string or element: EventTarget can make a bit more sense. This is especially helpful for functions with more overloads (it admittedly doesn't look to add much for a toy example like this one)
  • The overload allows for different sorts of return values given different argument types. The example could be slightly tweaked to be
export interface Selectors {
    select: {
      (selector: string): number;
      (element: EventTarget): string;
    };
}

which then wouldn't give as much type information if translated to

export interface Selectors {
    select (selectorOrElement: string | EventTarget): number | string;
}

because it doesn't indicate which argument is associated with which return type.

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

3 Comments

Ah, that makes sense. Preserving type information is an advantage with snippet1. However, I can't seem to write a class that implements Selectors 🤦‍♂️ I get Duplicate function implementation error (sandbox link). What am I missing?
There must be exactly one function body. select(selector: string | EventTarget): Selection { return new Selection(); }
Hmm... In that case, if the return types were different (like number and string) as you have mentioned above, select(selector: string | EventTarget): string | number { ... } doesn't seem to work :(

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.