What TypeScript pattern can I use to enforce that a function gets a property?

Posted by Matt York on Stack Overflow See other posts from Stack Overflow or by Matt York
Published on 2012-10-31T22:59:19Z Indexed on 2012/10/31 22:59 UTC
Read the original article Hit count: 215

Filed under:

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.

© Stack Overflow or respective owner

Related posts about TypeScript