What TypeScript pattern can I use to enforce that a function gets a property?
- by Matt York
In JavaScript I can do this:
function f() {}
f.prop = "property";
I want this in TypeScript, but with type checking.
What TypeScript pattern can I use to enforce that a function gets a property?
Could I use an interface?
interface functionWithProperty {
(): any;
prop: string;
}
This seems to be a valid interface in TypeScript, but how do I implement this interface such that the TypeScript compiler checks that prop is set?
I saw this example:
var f : functionWithProperty = (() => {
var _f : any = function () { };
_f.prop = "blah";
return _f;
}());
But this doesn't work because I can remove _f.prop = "blah"; and everything will still compile. I need to enforce that prop is set.