In JavaScript I can do this:
function f() {}
f.prop = "property";
I want this in TypeScript, but with type checking.
Other than classes, 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.
I think you need to embrace the object orientation in TypeScript and create a class with properties and functions.
Combining functions and properties as you have in your example is valid JavaScript, but if you are taking the leap into TypeScript you may as well get fully immersed in it.
Update
Disclaimer: I don’t recommend doing things this way – as I’ve said, I recommend using the structural features of TypeScript to organise your code in the most readable way you can.
However, you can define the type of your function if you want to using a type declaration:
This allows the callers of
fto get auto-completion and type checking, but won’t result in the contents offbeing checked to ensure it complies – because you are “under the hood” at this stage – so you could write this…If you want to get type checking on the definition of
fas well as having calls tofchecked, you’ll need to look at classes.