Reducing JavaScript Objects to Interface Properties
TypeScript interfaces define contracts for objects and ensure type safety. However, sometimes you may need to ensure that an object contains only the properties specified by an interface.
Problem:
Consider the following TypeScript code:
<code class="ts">interface MyInterface { test: string; } class MyTest implements MyInterface { test: string; newTest: string; } const test: MyTest = { test: "hello", newTest: "world" }; const reduced: MyInterface = test; // reduced still contains "newTest"</code>
Why is this problematic?
When using Angular's toJson method before making a REST call, the extra property (newTest) is included in the JSON, which can cause issues with the receiving service.
Solution 1: Workaround
James Moey provides an elegant workaround: declare the interface as a class instead, and use Lodash to pick only the interface properties from the object:
<code class="ts">class MyInterface { test: string = undefined; } import _ from 'lodash'; let reduced = new MyInterface(); _.assign(reduced, _.pick(before, _.keys(reduced)));</code>
This solution allows you to retain type safety while ensuring that the resulting object has only the interface properties.
Solution 2: Interface Helper Functions
Another approach is to create helper functions that validate objects against interfaces. For example:
<code class="ts">interface MyInterface { test: string; } function reduceObject(obj: any, targetInterface: any): MyInterface { const reduced = {}; Object.keys(targetInterface).forEach((key) => { if (obj[key] !== undefined) { reduced[key] = obj[key]; } }); return reduced; } const test: MyTest = { test: "hello", newTest: "world" }; const reduced: MyInterface = reduceObject(test, MyInterface);</code>
This approach uses loop introspection to validate objects against an interface and avoids the overhead of Lodash's pick function.
The above is the detailed content of How to Ensure JavaScript Objects Contain Only Interface Properties in TypeScript?. For more information, please follow other related articles on the PHP Chinese website!