Skip to content

Latest commit

 

History

History
88 lines (65 loc) · 3.32 KB

mirror-types-for-deps.md

File metadata and controls

88 lines (65 loc) · 3.32 KB

Item 70: Mirror Types to Sever Dependencies

Things to Remember

  • Avoid transitive type dependencies in published npm modules.
  • Use structural typing to sever dependencies that are nonessential.
  • Don't force JavaScript users to depend on @types. Don't force web developers to depend on Node.js.

Code Samples

// parse-csv.ts
import {Buffer} from 'node:buffer';

function parseCSV(contents: string | Buffer): {[column: string]: string}[]  {
  if (typeof contents === 'object') {
    // It's a buffer
    return parseCSV(contents.toString('utf8'));
  }
  // ...
}

💻 playground


// parse-csv.d.ts
import { Buffer } from 'node:buffer';
export declare function parseCSV(contents: string | Buffer): {
    [column: string]: string;
}[];

💻 playground


export interface CsvBuffer {
  toString(encoding?: string): string;
}
export function parseCSV(
  contents: string | CsvBuffer
): {[column: string]: string}[]  {
  // ...
}

💻 playground


parseCSV(new Buffer("column1,column2\nval1,val2", "utf-8"));  // OK

💻 playground


/** Anything convertible to a string with an encoding, e.g. a Node buffer. */
export interface StringEncodable {
  toString(encoding?: string): string;
}

💻 playground


import {Buffer} from 'node:buffer';
import {parseCSV} from './parse-csv';

test('parse CSV in a buffer', () => {
  expect(
    parseCSV(new Buffer("column1,column2\nval1,val2", "utf-8"))
  ).toEqual(
    [{column1: 'val1', column2: 'val2'}]
  );
});

💻 playground