TypeScript 3 Fundamentals, v2 Type Parameters
This course has been updated! We now recommend you take the TypeScript Fundamentals, v3 course.
Transcript from the "Type Parameters" Lesson
>> Mike North: We also have here, something like this syntax here. So I've been likening type perimeters to function arguments. Based on that analogy, can someone venture a guess as to what equals any means in this context?
>> Speaker 2: [INAUDIBLE]
>> Mike North: What's that?
>> Speaker 2: Default value is an any.
>> Mike North: Correct, if no type perimeter is provided, we fall back to an any.
[00:00:24] That is the default of this type parameter. So here, if we hover over this, this ends up being an any and this is sort of a filter for truth values. Sort of passes X straight through, it passes val straight through. And, as a result, this is what you could expect.
[00:00:45] You'll get no type errors for passing an argument to this, cause anything goes, right? So it's the equivalent of a default parameter value. It's just a default type.
>> Mike North: So, so far, in our examples, like in this example, we've declared that we have this type parameter, T, and we have found that we're using T directly.
[00:01:12] But you don't always have to do that, you're not limited to that. Here's an example, a little bit more complicated but one that I pulled out of my own code that,
>> Mike North: When passed a promise, and this is like the promise type is generic over the type that it resolves to.
[00:01:35] And when we say generic over that means that it is, it abstracts the type that it resolves to, it takes it as a type parameter. So you could have a promise that resolves to a number, or a promise that resolves to an HTTP response, right? That's what you get back when you call fetch.
[00:01:55] So T is the parameter, but I take as an argument Promise T and I'll infer what T must be based on the promise that I'm given and its type. So it takes a promises and argument and it takes a number as an argument, and it'll return a new promise that'll either time out if time's up.
[00:02:19] Or if the promise resolves before it time's up, it'll actually pass through the result value of that promise. And here is the implementation, should hopefully make sense. It's called setTimeout. This thing that setTimeout returns is necessary in order to cancel the timeout later on. And it's all set up, if nothing else happens, to reject the promise.
[00:02:45] If the promise resolves, we cancel the timeout. It's not finished, the callback that we passed to setTimeout may never get invoked. And then we resolve with the value. Note that I don't have to pass in anything with angle brackets here. And the reason is fetch returns a promise that resolves to a response.
[00:03:07] And so through receiving this an argument, type script figures out that T must be a response. It infers what T is by kind of plucking it out of the promise or the type of the promise.