Skip to content

Latest commit

 

History

History
121 lines (96 loc) · 4.03 KB

File metadata and controls

121 lines (96 loc) · 4.03 KB

Item 6: Use Your Editor to Interrogate and Explore the Type System

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'
}

💻 playground


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
}

💻 playground


let i = 0;
for (let i = 0; i < 10; i++) {
  console.log(i);
  {
    let i = 12;
    console.log(i);
  }
}
console.log(i);

💻 playground


let i = 0;
for (let x = 0; x < 10; x++) {
  console.log(x);
  {
    let i = 12;
    console.log(i);
  }
}
console.log(i);

💻 playground


declare function fetch(
  input: RequestInfo | URL, init?: RequestInit
): Promise<Response>;

💻 playground


interface Request extends Body {
  // ...
}
declare var Request: {
  prototype: Request;
  new(input: RequestInfo | URL, init?: RequestInit | undefined): Request;
};

💻 playground


interface RequestInit {
  body?: BodyInit | null;
  cache?: RequestCache;
  credentials?: RequestCredentials;
  headers?: HeadersInit;
  // ...
}

💻 playground