我应该如何创建自己的类型 DefinitelyTyped,默认类型为 class

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

我想为排名项目创建自己的 Typings DefinitelyTyped (https://github.com/maxcnunes/ranking)

我尝试了一些实现...

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;
}

当我尝试使用代码时

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

所以我用下面的代码再试一次...

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)
  }
}

然后尝试使用代码

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

不知道应该怎么做才能实现这个:(

好像Ranking是一个class,所以我也这样定义它:

custom-typings/ranking.d.ts

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

然后你可以这样称呼它:

app.ts

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

请注意使用 import Ranking = require('ranking') 而不是 import Ranking from 'ranking'。有关差异的完整讨论,请参考 this github issue

我也回答了一个,你可能想看看。