Iterate over interface properties in TypeScript

后端 未结 4 644
栀梦
栀梦 2020-12-15 15:09

I need to map interface properties to objects:

interface Activity {
  id: string,
  title: string,
  body: string,
  js         


        
4条回答
  •  余生分开走
    2020-12-15 15:46

    If you are okay with having it added during a compile time and you are using TypeScript >= 2.4.1, you can try the way proposed here.

    Basically, you should add the ts-transformer-keys dependency, custom transformer, like a basic one and you'll be able to list the properties like this:

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

提交回复
热议问题