'compile-time' way to get all property names defined interface

后端 未结 4 1376
心在旅途
心在旅途 2020-12-03 05:00

I\'d like to create a generic TypeScript class for rendering (as a HTML list) of an array of objects which implement a specific interface.

e.g.

4条回答
  •  Happy的楠姐
    2020-12-03 05:19

    This is possible by using custom transformers introduced by https://github.com/Microsoft/TypeScript/pull/13940, which is available in typescript >= 2.4.1.

    My npm package, ts-transformer-keys, is a good example.

    import { keys } from 'ts-transformer-keys';
    
    interface Props {
      id: string;
      name: string;
      age: number;
    }
    const keysOfProps = keys();
    
    console.log(keysOfProps); // ['id', 'name', 'age']
    

提交回复
热议问题