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'];
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With