TypeScript Library Types
Library types are the type packs the checker loads for a target, named by the lib setting. The DOM pack describes browser objects in type positions, so typed code can name their shapes without creating them.
Reading fields through a lib interface
Pick takes two members of the HTMLElement interface and builds a small shape. A plain literal fits that shape.
type LabelBits = Pick<HTMLElement, 'title' | 'lang'>;
const label: LabelBits = { title: 'Save', lang: 'en' };
console.log(label.title);
console.log(label.lang);A nullable element parameter
The parameter accepts an element or null, and the course creates no element. The null call takes the fallback branch.
function describe(el: HTMLElement | null): string {
if (el === null) {
return 'no element';
}
return el.title;
}
console.log(describe(null));Promise types for async values
The async function states Promise<string> as its return type. The awaited value is a plain string.
async function loadGreeting(): Promise<string> {
return 'ready';
}
async function main(): Promise<void> {
const greeting = await loadGreeting();
console.log(greeting);
}
main();Example
type CardBits = Pick<HTMLElement, 'title' | 'lang'>;
async function loadCard(): Promise<CardBits> {
return { title: 'Guide', lang: 'en' };
}
async function main(): Promise<void> {
const card = await loadCard();
console.log(card.title);
console.log(card.lang);
}
main();Key points
- The lib setting chooses which type packs the checker loads for the program.
- The DOM pack holds interfaces such as HTMLElement that describe browser objects.
- A lib type in a type position costs nothing at runtime, because types are erased.
- Pick over a lib interface builds a small local shape from a large described object.
- Promise<T> is a lib type that describes a value arriving later, with T as the arrived type.
In this example, a promise of a small shape picked from the HTMLElement interface resolves to a plain literal, and the program prints its two fields.
Note
This course runs under Node, so DOM types here describe shapes only and no browser object is ever created.
Try it Yourself
Edit the code, then press Run.
Running is simulated · TypeScript Playground
Exercise
What does the lib setting control?