Is there a best way to check an object against a typescript infterface?
I am working between two schemas, where one extends the other. I need to convert the extension back to base, and am doing so by deleting props from the extension to shape it to the original base class. An example:
interface Base {
prop1: string
prop2?: string
prop3?: string
}
interface Extended extends Base {
prop4: string
prop5: string
}
So in order to get Extended
back to Base
, I need to delete
props prop4
and prop5
This is of course easy enough to do, but, I need to ensure that the final result conforms to the Base
class, since deleting props does not tell the compiler anything, and the extension will pass the Base
type check.
I have looked at using a type guard, and other alternatives, however, I have not found a way to do this which accommodates for the optional properties found in Base
, or a seemingly efficient way to do it.
Here is a basic plan for the type guard as well as handling optional props:
function isBase(arg: any): arg is Base {
return arg
&& arg.prop1
&& (arg.prop2 || true)
&& (arg.prop3 || true)
}
Besides being a lot of work for a lot of props, it's brittle. Soon as Base
changes, this technique no longer works as intended. I feel like there is (should be) some Typescript way via utility types that could check the props against the Base
interface, so it will always work as intended.
Update
I found this. Looks very close but could not get it working with interfaces.