Paul Everitt
Paul Everitt

Reputation: 671

Typescript definitions, ES6 class, and constructors

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.

Upvotes: 6

Views: 3795

Answers (1)

Bruno Grieder
Bruno Grieder

Reputation: 29884

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'

Upvotes: 7

Related Questions