创建(我自己的)TypeScript库

时间:2016-04-12 14:18:03

标签: javascript typescript

按照this page上的教程 我有以下JavaScript:

function A(id) {
    var about = {
        Version: "0.0.0.1",
    };

    if (id) {
        if (window === this) {
            return new A(id);//<-Error in typescript
        }

        this.e = document.getElementById(id);
        return this;
    } else {
        return about;
    }
};

A.prototype = {
    doSomething: function () {
        //Some logic
        return this;
    }
}

JavaScript用法:

var result = A("test");//The type of result should be 'A'
result = new A("test");//The type of result should be 'A'
result = A("test").doSomething();//The type of result should be 'A'
result = new A("test").doSomething();//The type of result should be 'A'

我想创建一个基于TypeScript的库,它具有相同的用法。怎么办?

如果我试着把它放在&#39;&#39;文件和编译我得到一个错误说:错误TS2350:只能使用&#39; new&#39;来调用void函数。关键字。

此外,我不确定使用和不使用&#39; new&#39;关键字可以实现,因为我试图在打字稿中创建一个可以在javascript中使用的库,而不是让用户必须使用&#39; new&#39;关键字。

P.S。
我知道我可以使用&#39; .d.ts&#39;创建一个javascript文件。文件,但这不是目的。

2 个答案:

答案 0 :(得分:2)

TypeScript正在尝试协调A()的多种用途,并且没有足够的信息来确定您希望它看起来像什么。

This works

function A(id): void {
    if (window === this) {
        return new A(id);//<-Error in typescript
    }

    this.e = document.getElementById(id);
    return this;
};

let result = A("test");
result = new A("test").doSomething();

但添加版本返回块会让编译器感到困惑,因为A现在表现得像两个完全不同的东西。

如果您想强制编译器忽略投诉,您可以这样做:

function A(id): void {
    var about = {
        Version: "0.0.0.1",
    };

    if (id) {
        if (window === this) {
            return new A(id);//<-Error in typescript
        }

        this.e = document.getElementById(id);
        return this;
    } else {
        return <any>about;
    }
};

let result = A("test");
result = new A("test").doSomething();

但我不推荐它。您尝试做的是TypeScript试图防范的部分内容。我不知道如何在这个“正常工作”上打字。

编辑:在回复您的评论时,我建议更像这样的内容:

class A {
    public static about = {
        Version: "0.0.0.1"
    };

    private e: HTMLElement;

    constructor(id) {
        this.e = document.getElementById(id);
    }

    public doSomething() {
        //Some logic
        return this;
    }
}

let result = new A("test");
result.doSomething();

let about = A.about;

答案 1 :(得分:0)

感谢MrHen的帮助,这是我想出的最终代码:

pip install -r requirements.txt
相关问题