Get keys of a Typescript interface as array of strings

后端 未结 12 1703
攒了一身酷
攒了一身酷 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:44

    Maybe it's too late, but in version 2.1 of typescript you can use key of like this:

    interface Person {
        name: string;
        age: number;
        location: string;
    }
    
    type K1 = keyof Person; // "name" | "age" | "location"
    type K2 = keyof Person[];  // "length" | "push" | "pop" | "concat" | ...
    type K3 = keyof { [x: string]: Person };  // string
    

    Doc: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types

    0 讨论(0)
  • 2020-11-28 03:45

    You will need to make a class that implements your interface, instantiate it and then use Object.keys(yourObject) to get the properties.

    export class YourClass implements IMyTable {
        ...
    }
    

    then

    let yourObject:YourClass = new YourClass();
    Object.keys(yourObject).forEach((...) => { ... });
    
    0 讨论(0)
  • 2020-11-28 03:51

    This should work

    var IMyTable: Array<keyof IMyTable> = ["id", "title", "createdAt", "isDeleted"];
    

    or

    var IMyTable: (keyof IMyTable)[] = ["id", "title", "createdAt", "isDeleted"];
    
    0 讨论(0)
  • 2020-11-28 03:53

    You can't do it. Interfaces don't exist at runtime (like @basarat said).

    Now, I am working with following:

    const IMyTable_id = 'id';
    const IMyTable_title = 'title';
    const IMyTable_createdAt = 'createdAt';
    const IMyTable_isDeleted = 'isDeleted';
    
    export const IMyTable_keys = [
      IMyTable_id,
      IMyTable_title,
      IMyTable_createdAt,
      IMyTable_isDeleted,
    ];
    
    export interface IMyTable {
      [IMyTable_id]: number;
      [IMyTable_title]: string;
      [IMyTable_createdAt]: Date;
      [IMyTable_isDeleted]: boolean;
    }
    
    0 讨论(0)
  • 2020-11-28 03:55

    Can't. Interfaces don't exist at runtime.

    workaround

    Create a variable of the type and use Object.keys on it

    0 讨论(0)
  • 2020-11-28 03:55
    // declarations.d.ts
    export interface IMyTable {
          id: number;
          title: string;
          createdAt: Date;
          isDeleted: boolean
    }
    declare var Tes: IMyTable;
    // call in annother page
    console.log(Tes.id);
    
    0 讨论(0)
提交回复
热议问题