Home > Web Front-end > JS Tutorial > How can we reduce an object to conform to an interface in TypeScript?

How can we reduce an object to conform to an interface in TypeScript?

Mary-Kate Olsen
Release: 2024-11-01 03:58:02
Original
725 people have browsed it

How can we reduce an object to conform to an interface in TypeScript?

Object Reduction to Interface Conformity

In TypeScript, an interface defines a contract for an object's properties, while a class implements that interface. However, it's common to encounter objects with additional properties beyond those defined in an interface, which can pose challenges when using tools like JSON.stringify() that convert objects to JSON.

To address this, it's necessary to reduce an object such that it only contains properties from the interface it implements.

Problem:

When attempting to convert an object with additional properties to JSON using JSON.stringify(), the extra properties are included in the output, potentially invalidating the JSON.

Solution 1:

Due to the fact that TypeScript interfaces have no runtime representation and thus cannot be used to enforce property restrictions, a workaround is needed. By defining the interface as a class, we can use a library like Lodash to pick only the properties defined in the interface from the target object.

For example:

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

const reducedObj = new MyInterface();
_.assign(reducedObj, _.pick(originalObj, _.keys(reducedObj)));</code>
Copy after login

This method ensures that the reduced object contains only the properties defined in the interface.

Solution 2:

As another approach, one can manually loop through the target object's properties, checking if each property exists in the interface definition. If it does, the property is added to the reduced object. This method requires careful attention to avoid adding unintended properties.

While there is no direct way to enforce property conformity with TypeScript interfaces in JavaScript, these workarounds provide practical solutions to reduce objects to conform to interface definitions.

The above is the detailed content of How can we reduce an object to conform to an interface 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