Nick Jennings Nick Jennings - 1 month ago 7
TypeScript Question

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:

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:


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


The relevant portion of my
tsconfig.json
:

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

Answer

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.

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. Hope it helps :)