我有一个这样定义的变量:
interface MyObjects {
Troll : {
strength : string;
dexterity : string;
wisdom : string;
},
Child : {
health : string;
wellness : string;
},
Kitten : {
sneakFactor : string;
color : string;
}
}
let myObjects : MyObjects;
是否可以使用TypeScript填充 myObjects ,以便每个字符串都包含如下所示的完全限定名称:
myObjects.Troll.strength = 'Troll_strength';
myObjects.Troll.dexterity= 'Troll_dexterity';
myObjects.Troll.wisdom = 'Troll_wisdom';
myObjects.Child.health = 'Child_health';
//etc
更新1: 我希望使用Object.keys(myObjects)之类的东西来获取所有要迭代的键,但是我无法获取未初始化变量的键。
更新2: 通过使用以下方法,我得到了更进一步:
declare function keys<T extends object>() : Array<keyof T>;
const k = keys<MyObjects>();
我现在所有的键名都保存在k数组的根目录中。我可以像这样访问每个子对象:
myObjects[k]
...但是我现在不确定如何获取 myObjects [k] 的所有子属性的数组,因为我没有为每个属性定义类型。 / p>
答案 0 :(得分:1)
使用标准TS编译器是不可能的。 TypeScript类型在运行时已完全删除,因此该信息不再可用。
但是,如果您使用自定义脚本而不是仅使用tsc
来编译源代码,就可以实现。
为了简化代码,我在这里使用了ts-simple-ast。
这是个好主意吗?不,但是很有趣。
import { Project, VariableDeclaration, Type, WriterFunction } from 'ts-simple-ast' // ^21.0.0
const project = new Project()
project.addExistingSourceFiles('src/**/*.ts')
// Custom functionality
// Look for variables that have a doc comment with `@autoInit`
// Get their type, and assign values to https://stackoverflow.com/q/54260406/7186598
for (const sourceFile of project.getSourceFiles()) {
// TODO: Class properties, object literal properties, etc.?
const declarations = sourceFile.getVariableDeclarations()
for (const declaration of declarations.filter(hasAutoInitTag)) {
if (declaration.hasInitializer()) {
console.warn(`'${declaration.getName()}' has an initializer and @autoInit tag. Skipping.`)
continue
}
const type = declaration.getType()
const writer = createWriterForType(declaration.getName(), type);
const parentStatement = declaration.getParent().getParent()
const index = sourceFile.getStatements().findIndex(statement => statement === parentStatement)
// Insert after the variable declaration
sourceFile.insertStatements(index + 1, writer);
}
console.log(sourceFile.getFullText())
// Uncomment once you have verified it does what you want.
// sourceFile.saveSync()
}
// There's almost certainly a better way to do this.
function hasAutoInitTag(declaration: VariableDeclaration) {
// Comments are attached to a VariableDeclarationList which contains VariableDeclarations, so
// get the parent.
const comments = declaration.getParent().getLeadingCommentRanges().map(range => range.getText())
return comments.some(comment => comment.includes('@autoInit'))
}
function createWriterForType(name: string, type: Type): WriterFunction {
return writer => {
function writeTypeInitializer(nameStack: string[], type: Type) {
if (type.isString()) {
// Some logic for non-standard names is probably a good idea here.
// this won't handle names like '()\'"'
writer.writeLine(`${nameStack.join('.')} = '${nameStack.slice(1).join('_')}'`)
} else if (type.isObject()) {
writer.writeLine(`${nameStack.join('.')} = {}`)
for (const prop of type.getProperties()) {
const node = prop.getValueDeclarationOrThrow()
writeTypeInitializer(nameStack.concat(prop.getName()), prop.getTypeAtLocation(node))
}
} else {
console.warn('Unknown type', nameStack, type.getText())
}
}
writeTypeInitializer([name], type)
}
}
现在,不那么令人兴奋的解决方案。
您可以从一个对象生成该接口,而不是用一个接口描述您的对象。然后可以使用autoInit
函数访问这些键,该函数可以生成所需的字符串。 Playground demo
// Exactly the same as the original interface
type MyObjects = typeof myObjects
let myObjects = {
Troll: {
strength: '',
dexterity: '',
wisdom: ''
},
Child: {
health: '',
wellness: ''
},
Kitten: {
sneakFactor: '',
color: ''
}
};
autoInit(myObjects)
console.log(myObjects)
type AutoInitable = { [k: string]: AutoInitable } | string
function autoInit(obj: { [k: string]: AutoInitable }, nameStack: string[] = []) {
for (const key of Object.keys(obj)) {
const val = obj[key]
if (typeof val === 'string') {
obj[key] = [...nameStack, key].join('_')
} else {
autoInit(val, nameStack.concat(key))
}
}
}
问题adiga
的链接是另一个选择,由于它更通用,因此可能更好。您可以使用MyObjects['Troll']
访问子类型,但是我敢肯定您不能像使用上述两个选项一样自动进行任何深度的操作。