Par*_*xis 6 generics typescript
我正在编写一个简单的方法,它接受一个字符串作为参数,以便从对象中查找作为键。此方法具有泛型类型,将用于对返回的对象进行类型转换。然而,这并不像预期的那样工作。实际上是否可以对值进行类型转换,如果可以,我该怎么做?
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'
Run Code Online (Sandbox Code Playgroud)
uks*_*ksz -1
我认为你的方法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!");
}
}
Run Code Online (Sandbox Code Playgroud)
通过使用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'
Run Code Online (Sandbox Code Playgroud)
T编译好的JS里没有。它仅在预编译的 TypeScript 中可见。
除此之外,您无法调用:
getValue<VALUE>(...)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5866 次 |
| 最近记录: |