2015-12-10 44 views
3

随着Typescript 1.7和异步/等待支持的发布,我认为现在是用koa @ 2试用Typescript的好时机。针对ES6时的打字稿中的外部模块

我有一个非常简单的设置和它种工作已经:

// app.ts 

/// <reference path="../typings/koa.d.ts" /> 

import Koa from 'koa'; 

const app = new Koa(); 

因为KOA不打字稿写的,我不得不做出一个小的定义文件:

// koa.d.ts 
declare module 'koa' { 

    interface Context { 
    // ctx 
    } 

    export default class Koa { 
    constructor(); 

    listen(port: number): any; 
    use(Function: (ctx: Context, next:() => Promise<void>) => void): Function; 
    use(Function: (ctx: Context) => void): Function; 
    } 
} 

这一切在IDE中运行良好(没有错误,自动完成也可以)。然而,当我编译(目标=> ES6)到JavaScript中,编译的文件不能被执行:

// generated app.js 
var koa_1 = require('koa'); 
const app = new koa_1.default(); 

当我尝试运行它,我得到以下错误:

/Users/andreas/IdeaProjects/project/dist/app.js:16 
const app = new koa_1.default(); 
      ^

TypeError: koa_1.default is not a function 
    at Object.<anonymous> (/Users/andreas/IdeaProjects/project/dist/app.js:16:13) 
    at Module._compile (module.js:425:26) 
    at Object.Module._extensions..js (module.js:432:10) 
    at Module.load (module.js:356:32) 
    at Function.Module._load (module.js:313:12) 
    at Function.Module.runMain (module.js:457:10) 
    at startup (node.js:138:18) 
    at node.js:974:3 

它不起作用,因为koa_1.default()不是函数,它应该只是koa_1()。 (我也不确定它为什么重命名变量)。如果我在生成的app.js中进行这个简单的更改,那么一切正常。

我正在阅读很多与打字稿和外部模块相关的文章,但我似乎仍然错过了一些东西。我发现其中一个网站,这个例子:source

// foo.js 
export var bar = 'bar' 
export default 'foo'; 

// app.js 
import foo from './foo'; 
// foo => 'foo' 
import * as fooModule from './foo'; 
// fooModule => { bar: 'bar', default: 'foo' } 
import { default as defaultFoo } from './foo'; 
// defaultFoo => 'foo' 

这种解释为什么它添加.DEFAULT,但是从我的理解它是做什么的错误的情况。 (当我这样做import Koa from 'koa';这是不需要的,但是当我做import * as Koa from 'koa';

当我改变我的app.ts import语句import * as Koa from 'koa';生成的app.js的作品,但打字稿编译器和IDE给我下面的错误。

src/app.ts(13,13): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. 
src/app.ts(23,16): error TS7006: Parameter 'ctx' implicitly has an 'any' type. 
src/app.ts(23,21): error TS7006: Parameter 'next' implicitly has an 'any' type. 
src/app.ts(32,9): error TS7006: Parameter 'ctx' implicitly has an 'any' type. 

所以目前,我可以,如果我的开发环境下工作,或者如果产生的JavaScript的作品,但不能同时选择。

什么是解决这个问题的最好方法是什么?

我认为最简单的事情是将koa.d.ts定义文件更改为匹配import * as Koa from 'koa';。但是,我没有设法做到这一点。

感谢您的帮助!

+0

检查您是否遇到了[这里](http://stackoverflow.com/q/32987273/154066)讨论的问题,其中一个工具使用默认包装传入库,而另一个工具不包含。然后看看DefinitelyTyped上的几个库,看看他们如何编写defs - 我见过的那些不使用export default,通常更喜欢'export ='。 –

回答

0

更改此:

export default class Koa { 

使用import * as Koa语法这

class Koa { 
// ... 
namespace Koa { // add all your export interface inside 
// ... 
export = Koa; 

保持。