Skip to content

Instantly share code, notes, and snippets.

@adrienjoly
Created June 22, 2021 08:54
Show Gist options
  • Save adrienjoly/49060ce1efc3376609d710508d32838a to your computer and use it in GitHub Desktop.
Save adrienjoly/49060ce1efc3376609d710508d32838a to your computer and use it in GitHub Desktop.
Node.js code to extract the keys of a TypeScript type programatically
const ts = require("typescript")
/**
* Extract the keys of a type defined in a .d.ts file.
* @param filename - name of the .d.ts file
* @param namespace - namespace where the type is defined
* @param typeName - name of the type
* @param options - options to pass to the TypeScript parser
* @returns an array of keys, expressed as strings
*/
function extractTypeKeys (filename, namespace, typeName, options = {}) {
// reference documentation: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
const program = ts.createProgram([filename], options)
const sourceFile = program.getSourceFile(filename)
const symbols = program.getTypeChecker().getRootSymbols(sourceFile)
const envDef = symbols[0].locals.get(namespace).exports.get(typeName)
return envDef.declarations[0].type.members.map((envVar) => envVar.name.escapedText)
}
// example
const keys = extractTypeKeys("./sample-env-vars.d.ts", "MyApp", "RequiredEnvVars")
declare namespace MyApp {
type RequiredEnvVars = {
NODE_ENV: "development" | "production" | "test",
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment