Skip to content
Advertisement

Why does TypeScript use “Like” types?

Why does TypeScript have a type and then a “like type”? An example of this is Promise<T> and PromiseLike<T>.

What are the differences between these two types? When should I use them? In this case why not just have one Promise type?

Advertisement

Answer

If you look at the definition files (let’s take lib.es6.d.ts) then it’s pretty straight forward.

For example the ArrayLike interface:

JavaScript

is more limited than the Array one:

JavaScript

It’s good to have the two separated because I might want to have a function like this:

JavaScript

But it won’t work with this:

JavaScript

It results with this error:

Argument of type ‘IArguments’ is not assignable to parameter of type ‘any[]’.
Property ‘push’ is missing in type ‘IArguments’.

But both will work if I do this:

JavaScript

(more on ArrayLike in MDN)

The same with Promise and PromiseLike, if I’m building a library which isn’t opinionated about the implementation of the Promise then instead of doing this:

JavaScript

I’ll do this:

JavaScript

Then even if the user of my library is using a different implementation (bluebird) it will work just fine.

If you’ll notice the definition of Promise is this:

JavaScript

Which makes it very specific, other implementations might have different properties, for example a different prototype:

JavaScript

I guess that the main reason that we have PromiseLike is that several implementations were available before the native one was supported (such as bluebird, Promises/A+, jQuery, and more).
In order for typescript to work with code bases that are using those implementations there must be a type other than Promise, otherwise there would be a lot of contradictions.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement