0
votes

I'm trying to create type definition file for a library. The library is shipped to clients long time ago, so I can not change its code.

I'm using TypeScript 2.*

The library package exports a single factory function (using default export); The user can create instances of the lib using that factory function. What i use for lib.d.ts is

declare var _createLib: (config: Object) => Promise<Lib>;
export default _createLib;

export interface Lib {
    version: string;
}

And then I'm trying to use it in TypeScript like:

import LibFactory from 'lib';

LibFactory(configObject).then((actualLib: Lib => {
    // do some magic here
});

But it fails, because Lib type (the that of actualLib) is not defined.

There are two ways I can make it work, but I'm not sure these are proper solution:

1) Import all from Lib

import * as Lib from 'lib';

Lib.default(configObject).then((actualLib: Lib.Lib => {
});

2) Import default as some name, and any other type from the lib as named import

import {default as Factory, Lib as Lib} from 'lib';

Factory(configObject).then((actualLib: Lib=> {
});

I'm missing something? Is there a better way to create and use type definitions in that case?

1

1 Answers

1
votes

You'r right, in this case you should import both pieces. But this syntax should work as well for you:

import Factory, { Lib } from 'lib';

Factory(configObject).then((actualLib: Lib=> {
});

Also, if factory has right definition, you can omit specifying actualLib's type:

import Factory from 'lib';

Factory(configObject).then((actualLib => {
});

Typescript will know it's type.