Skip to content

Instantly share code, notes, and snippets.

@jhonnymoreira
Last active June 7, 2018 23:42
Show Gist options
  • Save jhonnymoreira/f9eea797cb8e007b8905b800baff8ddf to your computer and use it in GitHub Desktop.
Save jhonnymoreira/f9eea797cb8e007b8905b800baff8ddf to your computer and use it in GitHub Desktop.

This is an example on how to type (with TypeScript) Node.js functions that uses module.exports.

Code Structure

  • *.js has the module code written in JavaScript
  • *.d.ts has the module types
  • *.usage.ts has the JavaScript module usage in TypeScript

Examples

reverseString

An example on how to type a module with a single function (the default one) without having the export default ... syntax on its .d.ts file.

mathOperations

An example on how to type a module with multiple functions.

Esse é um exemplo em como tipar (com TypeScript) funções de Node.js que usam module.exports.

Estrutura de código

  • *.js contém o código do módulo, escrito em JavaScript
  • *.d.ts contém os tipos do módulo
  • *.usage.ts contém o uso do módulo JavaScript em TypeScript

Exemplos

reverseString

Um exemplo de como tipar um módulo com uma única função, a padrão (default), sem ter que usar a síntaxe export default ... no arquivo .d.ts desse módulo

mathOperations

Um exemplo de como tipar um módulo com multiplas funções.

export function add(x: number, y: number): number
export function subtract(x: number, y: number): number
const add = (x, y) => x + y
const subtract = (x, y) => x - y
module.exports = {
add,
subtract
}
import * as mathOperations from './mathOperations'
mathOperations.add(2, 2)
//=> 4
declare function reverseString(text: string): string
export = reverseString
const reverseString = text => text.split('').reverse().join('')
module.exports = reverseString
import reverseString = require('./reverseString')
reverseString('ABC')
//=> 'CBA'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment