2016-10-17 172 views
0
与定义的参数和属性的功能

我有一个类似如下的功能:在打字稿

var myFunction = function (config) { 
    var example = this.property; // just illustrating that we use `this` 
} 
myFunction.__reference = 'foobar'; 

现在我想要把它写在严格打字稿:

interface ExternalScope { 
    property: string; 
} 

interface ConfigObject { 
    name: string, 
    count: number 
} 

interface MyFunction { 
    (XHRLoader: this, cfg: ConfigObject): any; 
    __reference: string; 
} 

var myFunction = function (this: ExternalScope, config: ConfigObject): any { 
    var example = this.property; 
} 
myFunction.__reference = 'foobar'; 

使用上面的代码,我得到以下TypeScipt错误:

Property '__reference' does not exist on type '(this: ExternalScope: config: ConfigObject) => any

tsconfig.json相关部分:

"compilerOptions": { 
    "noEmitOnError": true, 
    "noImplicitAny": true, 
    "noImplicitReturns": true, 
    "noImplicitThis": true, 
    "strictNullChecks": true, 
    "noFallthroughCasesInSwitch": true, 
    "moduleResolution": "node", 
    "outDir": "./build", 
    "allowJs": false, 
    "target": "es5" 
}, 
+1

你还没有告诉TS'myFunction'是'MyFunction'的一个实例。 – deceze

+0

我该怎么做?我试过:之前的功能。但是我认为我有什么不对,因为这给了我更多的错误。 –

+0

'var myfunction:MyFunction = ...'会是最简单的。 – deceze

回答

0

这或许能有所帮助:

interface ExternalScope { 
    property: string; 
} 

interface ConfigObject { 
    name?: string, 
    count?: number 
} 

interface MyFunction { 
    (XHRLoader: this, cfg: ConfigObject): any; 
    __reference?: string; 
} 

var myFunction: MyFunction = function (this: ExternalScope, config: ConfigObject): any { 
    var example = this.property; 
} 

myFunction.__reference = 'foobar'; 

即使myFunction: myFunction创建你需要给它分配更多的错误。

当你根本

var myFunction = function (this: ExternalScope, config: ConfigObject): any { 
    var example = this.property; 
} 

打字稿试图推断myFunction变量的类型,因为它无法看到分配的功能的任何__reference性质,推断出的类型不包含它的。 希望它有帮助:)

+0

当我试图解决原始错误之前,但我又有两个额外的错误:'类型'(这个:ExternalScope,config:ConfigObject):任何'不能分配键入'MyFunction'。属性'__reference'在类型'(this:ExternalScope,config:ConfigObject)=> any'' ...中缺少,我也得到:'后续变量声明必须具有相同的类型。变量'myFunction'必须是'MyFunction'类型,但是这里有类型'(this:ExternalScope,config:ConfigObject)=> any''。 –

+0

这实际上有点难以理解你的评论中的错误。至于'type __reference'在类型中缺少的问题正在发生,因为当您定义变量'myFunction'的值时,打字稿在定义中找不到变量'__reference'。在我的解决方案中,我已经声明'__reference'是一个可选变量,因此不会发生错误。如果你愿意,你可以将我的代码复制并粘贴到[typescript playground](http://www.typescriptlang.org/play/)并确认其中没有错误 –

+0

啊,我没注意到添加了什么?在接口中。应用那些工作。谢谢! –