Search code examples
typescriptinterfacepropertiescompiler-constructionundefined

Use TS Compiler API to Determine if Interface property signature allows undefined (eg prop1?: string;)


I am using the TypeScript Compiler API to harvest Interface details so I can create database tables. Works well but I would like to identify whether fields are nullable, or in TS jargon, have a type guard like string|undefined.

Eg

export default interface IAccount{
name: string;
description?: string;

}

I would like to be able to identify property "description" as string|undefined and hence, "nullable". I can access the node text via the compiler API and find "?" but is there a better way?


Solution

  • The InterfaceDeclaration node contains node.members (PropertySignature nodes) and if such property signature contains a questionToken key, it is nullable:

    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}`);
    }
    

    Output:

    name is not nullable
    description is nullable