Get keys of a Typescript interface as array of strings

后端 未结 12 1751
攒了一身酷
攒了一身酷 2020-11-28 03:05

I\'ve a lot of tables in Lovefield and their respective Interfaces for what columns they have.
Example:

export interface IMyTable {
  id: number;
  t         


        
12条回答
  •  盖世英雄少女心
    2020-11-28 03:40

    This was a tough one! Thank you, everyone, for your assistance.

    My need was to get keys of an interface as an array of strings to simplify mocha/chai scripting. Not concerned about using in the app (yet), so didn't need the ts files to be created. Thanks to ford04 for the assistance, his solution above was a huge help and it works perfectly, NO compiler hacks. Here's the modified code:

    Option 2: Code generator based on TS compiler API (ts-morph)

    Node Module

    npm install --save-dev ts-morph
    

    keys.ts

    NOTE: this assumes all ts files are located in the root of ./src and there are no subfolders, adjust accordingly

    import {
      Project,
      VariableDeclarationKind,
      InterfaceDeclaration,
    } from "ts-morph";
    
    // initName is name of the interface file below the root, ./src is considered the root
    const Keys = (intName: string): string[] => {
      const project = new Project();
      const sourceFile = project.addSourceFileAtPath(`./src/${intName}.ts`);
      const node = sourceFile.getInterface(intName)!;
      const allKeys = node.getProperties().map((p) => p.getName());
    
      return allKeys;
    };
    
    export default Keys;
    
    

    usage

    import keys from "./keys";
    
    const myKeys = keys("MyInterface") //ts file name without extension
    
    console.log(myKeys)
    

提交回复
热议问题