Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract the properties of an interface using TypeScript (preferably with no 3rd party libs)

I need to get the properties of an interface to make sure that they match an object that implements it. For unit testing purposes.

So if changes are made to the interface the unit test should break if it isn't updated with the new members.

I've tried using the ts-transformer-keys package but it throws an error about not being a function.

   interface Test {
      mem1: boolean,
      mem2: string
   }

I would like to do something like this:

   console.log(Object.keys(Test))

and expect

   ['mem1', 'mem2'];
like image 770
DaNe505 Avatar asked Oct 25 '25 00:10

DaNe505


1 Answers

Interfaces don't exist at runtime, so extracting any information from an interface at run-time is not possible. You can create an object that has all the keys of the interface. The compiler will force you to specify all keys and will check that no extra keys are present so the duplication will never be out of sync with the interface:

interface Test {
    mem1: boolean,
    mem2?: string
}


function interfaceKeys<T>(keys: Record<keyof T, 1>) {
    return Object.keys(keys) as Array<keyof T>
}

console.log(interfaceKeys<Test>({
    mem1: 1,
    mem2: 1
}))

console.log(interfaceKeys<Test>({ // error
    mem1: 1,
}))

console.log(interfaceKeys<Test>({
    mem1: 1,
    mem2: 1,
    mem3: 1,     // error 
}))

play

like image 75
Titian Cernicova-Dragomir Avatar answered Oct 26 '25 14:10

Titian Cernicova-Dragomir