我有以下旧版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。
答案 0 :(得分:4)
我认为RED
,GREEN
和BLUE
被视为价值不会改变。
首先,您可以明确说明每种类型 - 每种类型都有字符串文字类型:
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;