在TypeScript中使用参数和属性定义函数

时间:2016-10-17 15:59:08

标签: javascript typescript

我有一个看起来像这样的功能:

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

现在我正在尝试用严格 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';

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

  

属性'__reference'在类型'上不存在(this:ExternalScope:   config:ConfigObject)=>任何

tsconfig.json的相关部分:

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

1 个答案:

答案 0 :(得分: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;
}

typescript尝试推断myFunction变量的类型,并且由于它在指定的函数中看不到任何__reference属性,因此推断类型也不包含它。 希望它有所帮助:)

相关问题