Home > Web Front-end > JS Tutorial > body text

How to Reduce JavaScript Objects to Only Interface Properties in TypeScript?

Patricia Arquette
Release: 2024-10-31 06:12:01
Original
636 people have browsed it

How to Reduce JavaScript Objects to Only Interface Properties in TypeScript?

Reducing JavaScript Objects to Interface Properties

When working with TypeScript, we often encounter the need to reduce JavaScript objects to only contain properties declared in an interface. This is especially useful when sending data to REST services that expect a specific schema.

Consider the following interface:

<code class="typescript">interface MyInterface {
  test: string;
}</code>
Copy after login

And an implementation that includes an additional property:

<code class="typescript">class MyTest implements MyInterface {
  test: string;
  newTest: string;
}</code>
Copy after login

The issue arises when we attempt to use Angular's toJson method to serialize the MyTest instance for sending to a REST service. The toJson method includes the newTest property, which is not part of the interface. This can lead to errors on the server side.

To resolve this issue, we need to find a way to reduce the MyTest instance to only contain the properties declared in the MyInterface interface. However, this is not possible directly because interfaces in TypeScript are essentially placeholders that have no runtime representation.

Instead, we can employ a workaround. One approach is to define the interface as a class with property initializers:

<code class="typescript">class MyInterface {
  test: string = undefined;
}</code>
Copy after login

Using this class as the interface, we can then use a library such as Lodash to pick only the properties that match the interface:

<code class="typescript">import _ from 'lodash';

const before = { test: "hello", newTest: "world"};
let reduced = new MyInterface();
_.assign(reduced , _.pick(before, _.keys(reduced)));
console.log('reduced', reduced); // { test: "hello" }</code>
Copy after login

This solution effectively reduces the MyTest instance to only include the properties declared in the MyInterface interface, providing a simple and pragmatic solution to the challenge.

The above is the detailed content of How to Reduce JavaScript Objects to Only 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!