1

I need to get types from an interface by doing something like below, but I need to do it inside a function. Is there any way to do this using typescript generics?

I need the function to pass request bodies, along with an interface specifying their types and verify that the request body has the necessary items as well as correct format.

Note: I am using tsoa with express, so any other library or technique to properly validate request bodies would be fine.

interface someInterface {
    foo: string;
    bar: number;
}

const testObject: someInterface = req.body;

verifyObject(testObject);
/*
ensure foo and bar are of correct type, length etc.
(I will verify types, I just need a way of
getting the interface keys in a reusable function.)
*/

function verifyObject<T>(obj: T): void {
    class temp implements T {} // does not work
    const keys = Object.keys(new temp());
    // use keys
}
t348575
  • 674
  • 8
  • 19

1 Answers1

0

You almost have it - made a generic function, so its param will be the object of the Interface, and accessing keys of the object is, well, you know it:

function verifyObject<T>(obj: T): void {
  const keys = Object.keys(obj);
}

verifyObject<someInterface>(someObj);
Julius Dzidzevičius
  • 10,775
  • 11
  • 36
  • 81
  • but if `someObj` has only 2 out of say 5 properties in the interface, only those two will be retrieved using `Object.keys`. How do I get all of the properties, so that I can check whether `someObj` contains them. – t348575 Feb 13 '21 at 18:38
  • In your example Interface has two properties and both are not optional, so my answer is based on that – Julius Dzidzevičius Feb 14 '21 at 07:53