Home > Web Front-end > JS Tutorial > How to Reduce a JavaScript Object to Interface Properties in TypeScript?

How to Reduce a JavaScript Object to Interface Properties in TypeScript?

Mary-Kate Olsen
Release: 2024-11-01 01:55:27
Original
799 people have browsed it

How to Reduce a JavaScript Object to Interface Properties in TypeScript?

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;
}
Copy after login

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
Copy after login

Assebly Operator

Alternatively, you can also use the assembly operator:

let reduced = {...new MyInterface(), ...test};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template