Search code examples
javascriptarraystypescripttypesinterface

Extract Generic Interface or Type keys as an Array


I want to know if it's possible to get a generic interface or type and get it's properties like an array of objects, like this:

interface UserData {
    email: string
}

keys = extractKeys<UserData>()

console.log(keys)  // [ 'email' ]

Solution

  • It is not possible to use an interface as a value-holding variable. But as a walkaround solution, you can achieve what you are looking for like below. This uses an approach where you have to define an object to hold data and via Object.keys() you fetch the keys of the Object you define.

    Refer the below code:

    const UserData = {
        email: '[email protected]',
        username: 'abc',
        age: 25,
        address:'123/Florida'
    };
    
    function extractKeys(obj) { 
        return Object.keys(obj);
    }
    
    console.log(JSON.stringify(extractKeys(UserData))); 

    Read more on Object.key() here.