6

I have a TypeScript project in which I'd like to use libmarkov from npm. It provides an ES6-importable class called Generator. You use it via new Generator('some text').

In my local project, I created a file typedefs/libmarkov.d.ts:

export class Generator {
    constructor(text: string);
    generate(depth: number);
}

I use typings to install it: typings install --save file:./typedefs/libmarkov.d.ts

However, this: let generator = new Generator('Foo Bar Baz');

...generates this compiler error:

Error:(5, 21) TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

I could change my constructor: constructor(text: string) {};

...but this gives:

Error:(2, 31) TS1183: An implementation cannot be declared in ambient contexts.

If it matters, I'm targeting TS 2.0.

2
  • Replace export with declare Commented Sep 12, 2016 at 15:46
  • If I replace with export, I still get the error about new. If I then add {} at the end of constructor, I still get the new error, but also get Error:(2, 31) TS1183: An implementation cannot be declared in ambient contexts. Commented Sep 12, 2016 at 16:15

1 Answer 1

7

Since this is a js library, I suspect you load it with something like

import {Generator} from "libmarkov"

In which case your external module definition must look like

declare module "libmarkov" {

    export class Generator {
        constructor(text: string);
        generate(depth: number);
    }
}

EDIT The definition is wrong; libmarkov seems to use a default export.

declare module "libmarkov" {

    export default class Generator {
        constructor(text: string);
        generate(depth: number);
    }
}

And the import would be

import Generator from 'libmarkov'
Sign up to request clarification or add additional context in comments.

6 Comments

Yes, that's what results under typings/modules/libmarkov/index.d.ts after I run typings. I guess typings wraps my libmarkov.d.ts in the declare module. However, I'm still stuck with the error about new.
The definition is wrong; libmarkov seems to use a default export. See edit above
Here's a question that might help me understand ambient/global etc. For this scenario (external ES6 module in node_modules), after I run my typings, should libmarkov wind up in typings/globals or typings/modules? Meaning, do I do typings --global --save or just typings -save?
Hmmm, not quite there. The commonjs that TypeScript generates says (to paraphrase) var libmarkov_1 = require('libmarkov'); new libmarkov_1.default('Foo Bar zBaz');. But .default is undefined.
Try const Generator = require('libmarkov'); new Generator('Foo Bar')
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.