Item 6: Use Your Editor to Interrogate and Explore the Type System
May 10, 2024 ยท View on GitHub
Things to Remember
- Take advantage of the TypeScript language services by using an editor that supports them.
- Use your editor to build an intuition for how the type system works and how TypeScript infers types.
- Familiarize yourself with TypeScript's refactoring tools, e.g., renaming symbols and files.
- Know how to jump into type declaration files to see how they model behavior.
Code Samples
function getElement(elOrId: string | HTMLElement | null): HTMLElement {
if (typeof elOrId === 'object') {
return elOrId;
// ~~~ Type 'HTMLElement | null' is not assignable to type 'HTMLElement'
} else if (elOrId === null) {
return document.body;
}
elOrId
// ^? (parameter) elOrId: string
return document.getElementById(elOrId);
// ~~~ Type 'HTMLElement | null' is not assignable to type 'HTMLElement'
}
function getElement(elOrId: string|HTMLElement|null): HTMLElement {
if (elOrId === null) {
return document.body;
} else if (typeof elOrId === 'object') {
return elOrId;
// ^? (parameter) elOrId: HTMLElement
}
const el = document.getElementById(elOrId);
// ^? (parameter) elOrId: string
if (!el) {
throw new Error(`No such element ${elOrId}`);
}
return el;
// ^? const el: HTMLElement
}
let i = 0;
for (let i = 0; i < 10; i++) {
console.log(i);
{
let i = 12;
console.log(i);
}
}
console.log(i);
let i = 0;
for (let x = 0; x < 10; x++) {
console.log(x);
{
let i = 12;
console.log(i);
}
}
console.log(i);
declare function fetch(
input: RequestInfo | URL, init?: RequestInit
): Promise<Response>;
interface Request extends Body {
// ...
}
declare var Request: {
prototype: Request;
new(input: RequestInfo | URL, init?: RequestInit | undefined): Request;
};
interface RequestInit {
body?: BodyInit | null;
cache?: RequestCache;
credentials?: RequestCredentials;
headers?: HeadersInit;
// ...
}