我正在使用 TypeScript 编译器 API 来收集接口详细信息,以便我可以创建数据库表。效果很好,但我想确定字段是否可以为空,或者用 TS 术语来说,是否有一个像 string|undefined 这样的类型保护。
例如
export default interface IAccount{
name: string;
description?: string;
}
我希望能够将属性“描述”识别为字符串|未定义,因此“可为空”。我可以通过编译器 API 访问节点文本并找到“?”但还有更好的办法吗?
InterfaceDeclaration
节点包含node.members
(PropertySignature
节点),如果此类属性签名包含questionToken
键,则它可以为空:
const str = `
interface IAccount {
name: string;
description?: string;
}
`;
const ast = ts.createSourceFile('repl.ts', str, ts.ScriptTarget.Latest, true /*setParentNodes*/);
const IAccount = ast.statements[0];
for (const member of IAccount.members) {
const name = member.name.getText();
let nullable = 'not nullable';
if (member.questionToken !== undefined) {
nullable = 'nullable';
}
console.log(`${name} is ${nullable}`);
}
输出:
name is not nullable
description is nullable