我有一个由我点击的html元素给出的字符串,并希望将我的对象强制转换为此类型。如何在没有每个字符串的开关案例的情况下做到这一点?
HTML示例
<button type="button" data-type="MyType">cast to MyType</button>
<button type="button" data-type="OtherType">caset to OtherType</button>
打字稿:
///<reference path="jquery.d.ts" />
class MyType {
// ... some declarations for this class
}
class OtherType {
// .. some declarations for this class
}
let obj = {
// compatible declations with one of the classes on top
}
$(document).ready(function(){
$('button').on('click', function(){
let typeString = $(this).attr('data-type');
obj = obj as typeString; // fails
obj = <typeString>obj // fails
switch(typeString) {
case 'MyType':
obj = obj as MyType;
break;
case 'OtherType':
obj = obj as OtherType;
breaks;
}
// this switch case works but looks too long on working with 200 possible response types
}
})
我知道对象是什么类型,因为通过调用其余的api来加载单击对象列表。但是如何转换呢?