我正在编写一个简单的方法,它接受一个字符串作为参数,从一个对象中查找一个键。此方法具有泛型类型,将用于对返回的对象进行类型转换。但是,这并不像预期的那样完全正常。是否有可能对类型进行类型转换,如果是,我该如何做?
class Application
{
private values : {[s : string] : string} = {
"foo" : "bar",
"test" : "1234"
}
public getValue<T>(key : string) : T
{
if (this.values.hasOwnProperty(key)) {
switch (typeof T) { // Doesn't work
case "string":
return this.values[key].toString();
case "number":
return parseInt(this.values[key]);
default:
throw new Error("Type of T is not a valid return type!");
}
} else {
throw new Error("Key '" + key + "' does not exist!");
}
}
}
var app : Application = new Application();
app.getValue<number>("test"); // Should return 1234
app.getValue<string>("test"); // Should return '1234'
答案 0 :(得分:0)
我认为您在方法中混淆了key
和T
。我会这样写:
public getValue<T>(key : string) : T
{
if (this.values.hasOwnProperty(key)) {
switch (typeof key) { // Doesn't work
case "string":
return this.values[key].toString();
case "number":
return parseInt(this.values[key]);
default:
throw new Error("Type of T is not a valid return type!");
}
} else {
throw new Error("Key '" + key + "' does not exist!");
}
}
使用playground可以更好地理解TypeScript的工作原理。您可以看到代码的编译方式:
var Application = (function () {
function Application() {
this.values = {
"foo": "bar",
"test": "1234"
};
}
Application.prototype.getValue = function (key) {
if (this.values.hasOwnProperty(key)) {
switch (typeof T) {
case "string":
return this.values[key].toString();
case "number":
return parseInt(this.values[key]);
default:
throw new Error("Type of T is not a valid return type!");
}
}
else {
throw new Error("Key '" + key + "' does not exist!");
}
};
return Application;
}());
var app = new Application();
app.getValue("test"); // Should return 1234
app.getValue("test"); // Should return '1234'
编译后的JS中没有T
。它只能在预编译的TypeScript中可见。
除此之外,您无法致电:
getValue<VALUE>(...)