Skip to content

Latest commit

 

History

History
157 lines (122 loc) · 5.65 KB

convert-up-the-graph.md

File metadata and controls

157 lines (122 loc) · 5.65 KB

Item 82: Convert Module by Module Up Your Dependency Graph

Things to Remember

  • Start migration by adding @types for third-party modules and external API calls.
  • Begin migrating your own modules from the bottom of the dependency graph upwards. The first module will usually be some sort of utility code. Consider visualizing the dependency graph to help you track progress.
  • Resist the urge to refactor your code as you uncover odd designs. Keep a list of ideas for future refactors, but stay focused on TypeScript conversion.
  • Be aware of common errors that come up during conversion. Move JSDoc types into TypeScript type annotations if necessary to avoid losing type safety as you convert.

Code Samples

async function fetchTable() {
  const response = await fetch('/data');
  if (!response.ok) throw new Error('Failed to fetch!');
  return response.json();
}

💻 playground


interface TabularData {
  columns: string[];
  rows: number[][];
}
async function fetchTable(): Promise<TabularData> {
  const response = await fetch('/data');
  if (!response.ok) throw new Error('Failed to fetch!');
  return response.json();
}

💻 playground


class Greeting {
  constructor(name) {
    this.greeting = 'Hello';
    //   ~~~~~~~~ Property 'greeting' does not exist on type 'Greeting'
    this.name = name;
    //   ~~~~ Property 'name' does not exist on type 'Greeting'
  }
  greet() {
    return `${this.greeting} ${this.name}`;
    //             ~~~~~~~~         ~~~~ Property ... does not exist
  }
}

💻 playground


class Greeting {
  greeting: string;
  name: any;
  constructor(name) {
    this.greeting = 'Hello';
    this.name = name;
  }
  greet() {
    return `${this.greeting} ${this.name}`;
  }
}

💻 playground


const state = {};
state.name = 'New York';
//    ~~~~ Property 'name' does not exist on type '{}'
state.capital = 'Albany';
//    ~~~~~~~ Property 'capital' does not exist on type '{}'

💻 playground


const state = {
  name: 'New York',
  capital: 'Albany',
};  // OK

💻 playground


interface State {
  name: string;
  capital: string;
}
const state = {} as State;
state.name = 'New York';  // OK
state.capital = 'Albany';  // OK

💻 playground


// @ts-check
/**
 * @param {number} num
 */
function double(num) {
  return 2 * num;
}

double('trouble');
//     ~~~~~~~~~
// Argument of type 'string' is not assignable to parameter of type 'number'

💻 playground


/**
 * @param {number} num
 */
function double(num) {
  return 2 * num;
}

double('trouble');  // OK

💻 playground


function double(num: number) {
  return 2 * num;
}

double('trouble');
//     ~~~~~~~~~
// Argument of type 'string' is not assignable to parameter of type 'number'

💻 playground