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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 06:12:01735browse

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>

And an implementation that includes an additional property:

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

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>

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>

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!

Statement:
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