[英]Defining a function with parameters and properties in TypeScript
I've got a function that looks like this: 我有一个看起来像这样的函数:
var myFunction = function (config) {
var example = this.property; // just illustrating that we use `this`
}
myFunction.__reference = 'foobar';
Now I'm trying to write it in strict TypeScript: 现在,我尝试使用严格的 TypeScript编写它:
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';
With the above code I get the following TypeScipt error: 使用上面的代码,我得到以下TypeScipt错误:
Property '__reference' does not exist on type '(this: ExternalScope: config: ConfigObject) => any
类型'(this:ExternalScope:config:ConfigObject)=> any不存在属性'__reference'
The relevant portion of my tsconfig.json
: 我的
tsconfig.json
的相关部分:
"compilerOptions": {
"noEmitOnError": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"strictNullChecks": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"outDir": "./build",
"allowJs": false,
"target": "es5"
},
Perhaps this can be of help: 也许这会有所帮助:
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';
Even though myFunction: myFunction
creates more errors you need to assign it. 即使
myFunction: myFunction
创建了更多错误,您仍需要对其进行分配。
when you simply do 当你只是做
var myFunction = function (this: ExternalScope, config: ConfigObject): any {
var example = this.property;
}
typescript tries to infer the type of the myFunction
variable and since it cannot see any __reference
property in the assigned function, the inferred type does not contain it either. typescript尝试推断
myFunction
变量的类型,并且由于它在分配的函数__reference
不到任何__reference
属性,因此推断的类型也不包含它。 Hope it helps :) 希望能帮助到你 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.