有没有办法找出interface的属性是否被定义为只读?说,
var ServerIP = window.localStorage.getItem('serverip');
if ( ping( ServerIP ) )
{
// Do Stuff
}
function ping(ip)
{
var img = new Image(1,1);
img.onload = function()
{
return true;
};
img.onerror = function()
{
return false;
};
img.src = "http://" + ip + "/pixel.png";
}
现在,TypeScript是否有某种反射或技巧来获取此信息?例如。类似的东西:
interface ITest {
readonly foo: number;
}
答案 0 :(得分:0)
由于TypeScript接口在运行时不存在,因此不能在它们上使用反射。为了使用反射,我创建了一个实现接口并反映在该类上的类。但是,我无法确定属性是否为只读。不知道这是我方面的不足还是缺陷。这是我尝试过的:
代码
interface ITest {
readonly foo: number;
bar: number;
}
class TestImplementation implements ITest {
readonly foo: number = 1;
bar: number = 2;
}
function reflectOnTest() {
var testImplementation = new TestImplementation();
var properties: string[] = Object.getOwnPropertyNames(testImplementation);
var fooDescriptor = Object.getOwnPropertyDescriptor(testImplementation, properties[0]);
var barDescriptor = Object.getOwnPropertyDescriptor(testImplementation, properties[1]);
console.log("foo writable = " + fooDescriptor.writable);
console.log("bar writable = " + barDescriptor.writable);
}
输出为:
foo writable = true
bar writable = true