【问题标题】:How to implement prototype-less constructors in Typescript?如何在 Typescript 中实现无原型构造函数?
【发布时间】:2016-07-06 20:18:07
【问题描述】:

有没有办法在 TS 中复制以下 JS 模式并保证类型安全?

function InputStream(input) {
    var pos = 0, line = 1, col = 0;
    return {
        next  : next,
        peek  : peek,
        eof   : eof,
        croak : croak,
    };
    function next() {
        var ch = input.charAt(pos++);
        if (ch == "\n") line++, col = 0; else col++;
        return ch;
    }
    function peek() {
        return input.charAt(pos);
    }
    function eof() {
        return peek() == "";
    }
    function croak(msg) {
        throw new Error(msg + " (" + line + ":" + col + ")");
    }
}

如果我添加类型提示,我会得到:

function InputStream(input: string) {
    var pos = 0
    var line = 1
    var col = 0

    return {
        next,
        peek,
        eof,
        croak
    }

    function next(): string {
        var ch = input.charAt(pos++);
        if (ch == "\n") line++, col = 0; else col++;
        return ch;
    }

    function peek(): string {
        return input.charAt(pos);
    }

    function eof(): boolean {
        return peek() == "";
    }

    function croak(msg):string {
        throw new Error(`${msg} (${line}:${col})`);
    }
}

TS 将推断返回对象的接口,因此使用 InputStream 是类型安全的 - 到目前为止,一切都很好。

我的问题是,似乎没有任何方法可以将参数类型提示为接口的实例?

例如(当然)这是行不通的:

function TokenStream(input: InputStream) {
    // ...
}

有没有办法将input 参数类型提示为InputStream 函数的返回类型

我的意思是,没有明确声明接口,这似乎是多余的,因为它能够推断接口。

当然,我也可以将它移植到一个真实的类中——这看起来更“正确”,但会使code like this 非常冗长。

有没有其他方法可以实现类似的东西,也许是模块?我注意到模块能够调用模块中声明的函数而无需使用 this 限定,并且经常希望通过类方法和父类实现这一点,但 TS 团队拒绝了该请求。

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    如果您在其他地方需要它的类型,您真的想键入 InputStream 返回值,它也是很好的文档。您要求的是某种元数据,例如“给我该函数返回的类型”,我认为 typescript 没有这种功能。

    推理最好留给小 lambda 函数 imo。

    作为参考,您可以执行以下操作:

    const input = InputStream('abcd')
    
    function TokenStream(input2: typeof input) {
    
    }
    

    但是您需要一个实际值来键入第二个函数的参数,这很奇怪,可能不是您想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 2016-08-02
      • 2020-07-24
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      相关资源
      最近更新 更多