Skip to content

Instantly share code, notes, and snippets.

@framp
Last active September 3, 2020 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save framp/2ea50fb6b13d6f355b35b3829dace2a4 to your computer and use it in GitHub Desktop.
Save framp/2ea50fb6b13d6f355b35b3829dace2a4 to your computer and use it in GitHub Desktop.
Get a list of keys from a TS interface (and kill some kittens on the way)
// npm install --save recast babylon@next @types/node
import * as recast from "recast";
import * as typescriptParser from "recast/parsers/typescript";
import * as fs from "fs";
export interface IMyTable {
id: number;
title: string;
createdAt: Date;
isDeleted: boolean;
}
const ast = recast.parse(fs.readFileSync(__filename).toString(), {
parser: typescriptParser,
});
const keys = ast.program.body
.find(
(node) =>
node?.declaration?.type === "TSInterfaceDeclaration" &&
node?.declaration?.id?.name === "IMyTable"
)
.declaration.body.body.map((keyNode) => keyNode.key.name);
console.log(keys); //[ 'id', 'title', 'createdAt', 'isDeleted' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment