如何使用Typescript 1.4.0获取对象属性的类型。
我正在搜索类似于C#的东西,它可以查找对象的属性。
var properties = typeof(T).GetProperties();
foreach( var property in properties){}
到目前为止我所拥有的是:
var ls = ts.createLanguageService(host, ts.createDocumentRegistry())
var nav = ls.getNavigationBarItems(host.fileName);
给出示例Interface:
interface Example {
firstname: string;
lastname: string;
age: string;
}
TypeScript语言服务返回结果:
{
"NavigationBarItems":[
{
"text":"Example",
"kind":"interface",
"kindModifiers":"",
"spans":[
{
"start":0,
"length":83
}
],
"childItems":[
{
"text":"age",
"kind":"property",
"kindModifiers":"",
"spans":[
{
"start":69,
"length":12
}
],
"childItems":[
],
"indent":0,
"bolded":false,
"grayed":false
},
{
"text":"firstname",
"kind":"property",
"kindModifiers":"",
"spans":[
{
"start":24,
"length":18
}
],
"childItems":[
],
"indent":0,
"bolded":false,
"grayed":false
},
{
"text":"lastname",
"kind":"property",
"kindModifiers":"",
"spans":[
{
"start":47,
"length":17
}
],
"childItems":[
],
"indent":0,
"bolded":false,
"grayed":false
}
],
"indent":0,
"bolded":false,
"grayed":false
}
]
}
我缺少的信息是类型(字符串,数字,地图<>,any)以及它是否是数组或对象,例如
"text":"lastname",
"kind":"property",
"type":"string", //string,number,Map<>,any
任何想法如何实现这一目标?
非常感谢您的帮助。
答案 0 :(得分:2)
找到解决方案,不知道我是如何错过它的。 Nicholas Wolverson有一篇关于它的博文。使用TypeScript语言服务不是正确的选择。正确的解决方案是使用TypeScript编译器API。
var program = ts.createProgram([dummyScriptName], host.getCompilationSettings(), host);
var typeChecker = program.getTypeChecker(true);
var sf = program.getSourceFile(dummyScriptName);
var decls = sf.getNamedDeclarations().map(function (nd) { return nd.symbol.name + ": " + typeChecker.typeToString(typeChecker.getTypeAtLocation(nd)); });
这将返回所需的信息
interface Person {
firstname: string;
lastname: string;
age: number[];
}
结果:
Person: Person
firstname: string
lastname: string
age: number[]
请使用(code,mirror_code,blog post)了解详情。