Typescript 我可以使用什么类型脚本模式强制函数获取属性?

Typescript 我可以使用什么类型脚本模式强制函数获取属性?,typescript,Typescript,在JavaScript中,我可以做到这一点: function f() {} f.prop = "property"; 我想在TypeScript中使用这个,但是需要进行类型检查 除了类之外,我可以使用什么类型脚本模式来强制函数获取属性? 我可以使用接口吗 interface functionWithProperty { (): any; prop: string; } 在TypeScript中,这似乎是一个有效的接口,但如何实现该接口,以便TypeScript编译器检查pr

在JavaScript中,我可以做到这一点:

function f() {}
f.prop = "property";
我想在TypeScript中使用这个,但是需要进行类型检查

除了类之外,我可以使用什么类型脚本模式来强制函数获取属性?

我可以使用接口吗

interface functionWithProperty {
    (): any;
    prop: string;
}
在TypeScript中,这似乎是一个有效的接口,但如何实现该接口,以便TypeScript编译器检查
prop
是否已设置

我看到:


但这不起作用,因为我可以删除
\u f.prop=“blah”并且所有内容仍将编译。我需要强制设置
prop

我认为您需要在TypeScript中采用对象定向,并创建一个具有属性和函数的类

将示例中的函数和属性组合在一起是有效的JavaScript,但是如果您正在跳入TypeScript,那么您也可以完全沉浸在其中

class MyClass {
    constructor(public myProp: string) {
    }

    myFunc(): string{
        return this.myProp;
    }
}
更新

免责声明:我不建议这样做-正如我所说的,我建议使用TypeScript的结构特性以最可读的方式组织代码

但是,如果要使用类型声明,可以定义函数的类型:

var f: { (): void; prop: string; } = (() => {
    var _f : any = function () { 
        alert(_f.prop);
    };
    _f.prop = "blah";
    return _f;
}());

f();
这允许
f
的调用者获得自动完成和类型检查,但不会导致
f
的内容被检查以确保其符合要求-因为您在这个阶段处于“隐藏”状态-因此您可以编写此

var f: { (): void; prop: string; } = (() => {
    var _f : any = undefined;
    return _f;
}());

f();

如果您希望对
f
的定义进行类型检查,并检查对
f
的调用,则需要查看类。

您可以通过利用和使用完整的类型信息来干净地管理它

这个例子看起来很像你在问题中给出的例子,但是TypeScript编译器将确切地知道发生了什么!基本上,mycolfunc的模块声明被添加到函数声明中,从而生成一个具有属性的函数


如果您想在编译时断言MyColfunc正确地实现functionWithProperty,您可以在模块中有一个未报告的变量声明,如上例所示。

并使其实现该接口:类MyClass实现functionWithProperty以在缺少prop时获得错误。谢谢。这是一个合理的建议,但我明确地试图在没有类的情况下实现它。@MattYork,那么TypeScript可能不是实现它的工具。@MattYork-我已经添加了一些关于如何执行您所描述的操作的细节,但它只会让你检查呼叫者的类型,作为更新,你可以按照他在问题的第二个例子中所展示的方法来做。
var f: { (): void; prop: string; } = (() => {
    var _f : any = undefined;
    return _f;
}());

f();
interface functionWithProperty {
    (): any;
    prop: string;
}


function MyCoolFunc() {
    return "yay";
}

module MyCoolFunc {
    export var prop: string = "wow";
}

// this will compile without errors, MyCoolFunc implements the
// functionWithProperty interface (structurally)
let x: functionWithProperty = MyCoolFunc;

console.log(x.prop, x());
console.log(MyCoolFunc.prop, MyCoolFunc());

// this would result in a compiler error
// let y: functionWithProperty = console.log;