打字稿全局枚举?

时间:2017-07-11 23:00:52

标签: typescript

我有以下旧版javascript:

getProduct(id: number): Observable<IProduct> {
    if (id === 0) {
        return Observable.of(this.initializeProduct());
    };
    const url = `${this.baseUrl}/${id}`;
    return this.http.get(url)
        .map(this.extractData)
        .do(data => console.log('getProduct: ' + JSON.stringify(data)))
        .catch(this.handleError);
}

有没有办法在var RED = "red"; var GREEN = "green"; var BLUE = "blue"; function foo(color) { // color MUST be RED, GREEN, or BLUE } // eg... foo(RED); 文件中对此进行编码?

我无法更改javascript。

1 个答案:

答案 0 :(得分:4)

我认为REDGREENBLUE被视为价值不会改变。

首先,您可以明确说明每种类型 - 每种类型都有字符串文字类型

declare var RED: "red";
declare var GREEN: "green";
declare var BLUE: "blue";
  

注意:您甚至可能只想将这些声明声明为const声明。

然后,您可以根据以下内容创建Color类型:

type Color = typeof RED
           | typeof GREEN
           | typeof BLUE;

或者

type Color = "red"
           | "green"
           | "blue";

最后,只要您只接受其中一个值,请使用Color类型:

declare function foo(color: Color): any;