A test suite has a small helper that returns the first item of a list. It must work for any list, so someone typed it with any.
function first(items: any[]): any {
return items[0];
}
const title = first(["Dune", "Emma"]);
console.log(title.toFixed(2));
TypeError: title.toFixed is not a function
The list holds text. The code treats the first item as a number, and the compiler says nothing. The wording of the error is from the engine in Node and Chrome.
You know why from the Junior track: any switches checking off, and it spreads. The helper took a list of text and returned something with no type at all.
Typing it as string[] would fix this call. Then the helper would not work for a list of numbers, and you would write it twice.
A type parameter
function first<T>(items: T[]): T | undefined {
return items[0];
}
const title = first(["Dune", "Emma"]);
console.log(title.toFixed(2));
lists.ts(6,13): error TS18048: 'title' is possibly 'undefined'.
lists.ts(6,19): error TS2551: Property 'toFixed' does not exist on type 'string'. Did you mean 'fixed'?
Now the compiler reports the line, and for two reasons. Notice the suggestion at the end of the second error. The compiler guesses from names that look similar, and here the guess does not help.
Read the first line of the function one piece at a time.
<T>declares a type parameter. It is a placeholder for a type, and each call fills it in.items: T[]says the argument is a list of that type.T | undefinedsays the result is one item of that same type, or nothing when the list is empty.
At the call, the compiler looks at the argument. It is a list of text, so T is string for this call. The result is string | undefined. So title may be missing, and text has no toFixed.
A function with a type parameter is called generic. You did not write string anywhere. The compiler worked T out from the argument, as it infers the type of a variable from its value.
You have used generics already
Promise<Member> is a generic type that somebody else wrote. So is Partial, which you meet in the next lecture. string[] has a longer form, Array<string>, and it means the same.
You can write a generic type yourself. Here is the shape of a list that an API sends one page at a time.
interface Paged<T> {
items: T[];
total: number;
}
interface Book {
title: string;
copies: number;
}
const page: Paged<Book> = { items: [{ title: "Dune", copies: 3 }], total: 41 };
console.log(page.items[0].title + " of " + page.total);
Dune of 41
Paged<Book> is a page of books. Paged<Member> would be a page of members, with the same items and total. One interface describes both.
A generic that only asserts
Look at this helper. It is common in test projects.
function parse<T>(text: string): T {
return JSON.parse(text);
}
const book = parse<{ title: string; copies: number }>('{"title":"Dune"}');
console.log(book.copies);
undefined
It compiles. The response has no copies, and the code reads undefined from a field typed as a number.
Compare the two helpers. In first, T appears in the parameter and in the result. The compiler takes it from the argument, so the result type is something it worked out. In parse, T appears only in the result. Nothing that goes in decides it. You write it by hand at the call, and the compiler believes you.
That is the as from the Junior track, written with angle brackets. parse<Book>(text) checks nothing about the text.
Here is a quick test for any generic helper. Find where the type parameter appears. If it links an input to an output, the compiler is doing work. If it appears once, you are making a claim.
Remember this
A type parameter such as <T> is a placeholder that each call fills in, usually from the arguments. It lets one helper keep the type of what goes through it. A type parameter that appears only in the result is an assertion, and nothing checks it.
Reference: Generics in the TypeScript Handbook.