Ittipon Teerapruettikulchai Ittipon Teerapruettikulchai - 3 months ago 14
TypeScript Question

How should I do to create my own Typings DefinitelyTyped which have default as class

I want to create my own Typings DefinitelyTyped for Ranking project (https://github.com/maxcnunes/ranking)

I've try some implementation following...

declare module 'ranking' {
interface RankingPlayer {
position: number
score: number
playerId: any
}

interface Ranking {
maxScore: number
branchFactor: number
players: any
find(query);
findOne(query);
setScore(player: RankingPlayer);
addPlayerPoints(player: RankingPlayer);
}

interface RankingStatic {
(config: any): Ranking;
}

var ranking: RankingStatic;

export = ranking;
}


When I try with code

import Ranking from 'ranking'
...
console.log(Ranking) // This out '[Function: Ranking]'
const ranking = new Ranking({}) // This Error 'Cannot call a class as a function'


So I try again with the following codes...

declare module 'ranking' {
interface RankingPlayer {
position: number
score: number
playerId: any
}

export default class Ranking {
maxScore: number
branchFactor: number
players: any
constructor(config: any)
find(query)
findOne(query)
setScore(player: RankingPlayer)
addPlayerPoints(player: RankingPlayer)
}
}


And try with code

import Ranking from 'ranking'
...
console.log(Ranking) // This out 'undefined'
const ranking = new Ranking({}) // This Error 'ranking_1.default is not a constructor'


Don't know what should do to implement this :(

Answer

It seems like Ranking is a class, so I would also define it as such:

custom-typings/ranking.d.ts

declare module 'ranking' {
  class Ranking {
    constructor(options?: {})
  }
  export = Ranking
}

Then you can just call it like:

app.ts

import Ranking = require('ranking');
const ranking = new Ranking({
  maxScore: 1000000,
  branchFactor: 1000
});

Notice the use of import Ranking = require('ranking') instead of import Ranking from 'ranking'. For the full discussion on the difference, I refer you to this github issue.

Also I answered a very similar question, you might want to check out.

Comments