Augment types for imported module in TypeScript

Viewed 516

I'm converting an existing codebase from js/react/jsx setup to TypeScript. Naturally, I'd like to do it file by file, and have a question about approaches for making TS compiler work with the existing js codebase.

I convert file index.js but want to leave foo.js in JavaScript for now:

// index.ts

import { fooFunction } from 'foo';

foo({ val: 1 });

// foo.js

export const fooFunction = ({ val, optionalProp }) => {
  //...
}

The problem in this example that TypeScript automatically infers argument to foo and complains that Property 'optionalProp' is missing in type { val:string, optionalProp:any }

Needing to "stub" the type of fooFunction sent me looking and I found a few ways i may be able to do it:

1) Use require instead of import

// index.ts
var fooFunction: any = require('foo').fooFunction;

2) Merge declarations

?

3) Add a d.ts file with custom declarations for foo - haven't attempted but seems inconvenient

Ideally I don't have to do (1) because I want to keep using import syntax and I don't have to do (3) because that will require me to add declaration files only to remove them later when I'm ready to convert foo.

(2) sounds awesome, but I can't figure out a working solution.

// index.ts

declare module 'foo' {
  function fooFunction(options: any): any
}

Doesn't work and throws Cannot redeclare block-scoped variable 'fooFunction'

How do I do that? Are there docs that have examples of what I'm trying to do and/or have more explanation about declaration merging and how to work with namespace/interface/value? Are there better approaches for incrementally transitioning to TypeScript?

1 Answers
Related