Reducing JavaScript Object to Interface Properties
In TypeScript, an interface acts as a blueprint for data structures. However, during runtime, interfaces are empty, making it impossible to directly reduce an object to only contain properties defined in it.
Implementation
However, there are several workaround methods:
Using a Class
Define the interface as a class instead:
class MyInterface { test: string = undefined; }
Then, use Lodash to extract the required properties:
import _ from "lodash"; const before = { test: "hello", newTest: "world" }; let reduced = new MyInterface(); _.assign(reduced, _.pick(before, _.keys(reduced))); console.log("reduced", reduced); // contains only "test" property
Assebly Operator
Alternatively, you can also use the assembly operator:
let reduced = {...new MyInterface(), ...test};
This merges the empty "MyInterface" object with the "test" object, overwriting any duplicate properties.
Why Use This Method?
This approach is useful when sending data to REST services using Angular's "toJson" method. The "newTest" property, though inaccessible during compilation, would be transformed by "toJson," causing the REST service to reject the JSON due to invalid properties. By reducing the object to the interface properties, only the expected data is sent, ensuring proper communication with the service.
The above is the detailed content of How to Reduce a JavaScript Object to Interface Properties in TypeScript?. For more information, please follow other related articles on the PHP Chinese website!