Do you know of a more efficient way to write Typescript class and interface definitions?

In my TypeScript project, I'm creating a class with constructor parameters defined by an interface to limit the properties to only those that are specified.

Although the current code snippet achieves the desired functionality, I am looking for a way to streamline it and eliminate repetition. Each property is mentioned 4 times in the code, which seems redundant. Is there a more efficient approach?

interface MyInterface {
  property1: string;
  property2: boolean;
  property3: number;
}
class MyClass {
  property1: string;
  property2: boolean;
  property3: number;
  constructor(parameters: MyInterface) {
    this.property1 = parameters.property1;
    this.property2 = parameters.property2;
    this.property3 = parameters.property3;
  }
}

const example = new MyClass({property1: "Property 1", property2: true, property3: 3, extraProperty: "Shouldn't exist"});
console.log(example);

UPDATE: Additionally, I need to ensure that the properties are restricted at run-time to prevent objects with unknown additional properties.

Answer №1

What do you think about this code?

interface AnotherInterface {
    item1: string;
    item2: boolean;
    item3: number;
}

class AnotherClass implements AnotherInterface {
    item1: string;
    item2: boolean;
    item3: number;

    constructor(values: AnotherInterface) {
        Object.assign(this, values);
    }
}

Answer №2

In my opinion, this approach seems to offer a balance between brevity and efficiency. However, its effectiveness may vary depending on the specific requirements of your implementation—particularly whether the constructor's parameters will consistently align with the class properties. If there is potential for mismatch, utilizing an interface could provide a more organized solution.

class CustomClass {
    prop1!: string
    prop2!: boolean
    prop3!: number

    constructor(params: typeof CustomClass.prototype) {
        Object.assign(this, params)
    }
}

Answer №3

interface YourInterface {
  item1: string;
  item2: boolean;
  item3: number;
}

class YourClass implements YourInterface {
  constructor(
    public item1: string,
    public item2: boolean,
    public item3: number
  ) { }
}

const example = new YourClass("Item 1", true, 5, "Should not be included");
console.log(example);

By using public in the constructor parameters, I can avoid declaring them outside of the constructor function. The YourClass class adheres to the YourInterface interface to ensure all required properties are present.

This approach may not be suitable for your specific requirements as each property needs to be assigned manually in the constructor. Nonetheless, it could offer some valuable insights.

Answer №4

Absolutely, it is achievable but you must include the story class argument in the parameters property:

interface MyInterface {
  property1: string;
  property2: boolean;
  property3: number;
}
class MyClass {
  constructor(public parameters: MyInterface) {  }
}

const example = new MyClass({ property1: "Property 1", property2: true, property3: 3, extraProperty: "Shouldn't exist" });
console.log(example);

example.parameters.property1 // ok

Playground

Kindly note the usage of the public keyword I have included within the constructor

https://i.sstatic.net/ovNUp.png

If you wish to validate your object at runtime, you should consider implementing either user-defined type guards or io-ts

TypeScript boasts a static type system

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for integrating TypeScript files into Next.js HTML files

Encountering an issue while trying to load a typescript file from HTML, resulting in this error Here is the code snippet for the page: export default function Home() { return ( <> <Script src="/static/main.tsx"></Scri ...

Identify when the Vue page changes and execute the appropriate function

Issue with Map Focus Within my application, there are two main tabs - Home and Map. The map functionality is implemented using OpenLayers. When navigating from the Home tab to the Map tab, a specific feature on the map should be focused on. However, if th ...

Eliminate Elements from Array - Angular Four

I am currently developing a basic to-do app using Angular4. The setup of the app is structured as follows: Form Component: Responsible for adding items to the to-do list Item Component: Represents individual to-do items App Component: Contains a *ngFo ...

Mocking a promise rejection in Jest to ensure that the calling function properly handles rejections

How can I effectively test the get function in Jest, specifically by mocking Promise rejection in localForage.getItem to test the catch block? async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error(&apo ...

Exploring the powerful combination of React, Typescript, and the dynamic import Higher Order

import React from 'react' import { Preloader } from 'src/base-components/preloader' import styles from './styles.scss' const withLazyLoading = (importComponent: any) => { return class extends React.Component { ...

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

The successful completion of an Angular2 HTTP request relies on the data obtained from a previous response

I developed a service that performs various http calls with different parameters. quote.service.ts getQuotes(){ let params = { "Type": "BasicDetail", } return this.http.post(this.url,params) .map(res => res.json()) } getOptio ...

Encountering an error in TypeScript: Attempting to define type files for a third-party library triggers the TS2709 error when attempting to use the 'Optional' namespace as a type

Currently, I'm in the process of creating type files for a third-party library called optional-js. The structure is as follows: index.js var Optional = require('./lib/optional.js'); module.exports = { empty: function empty() { ...

Initiate asynchronous ngOnInit

Can ngOnInit() actually return a promise? I've noticed a common practice where developers use this approach and it appears to be functional. However, there is a risk with unobserved promises as they can be resolved or rejected at unexpected times, s ...

The parameter 'Barable' cannot be assigned to the parameter 'T' as they are not compatible

Could anyone help me understand why this code isn't functioning as intended: class Fooable { foo: string; } class Barable extends Fooable { bar: boolean; } function simplifiedExample<T extends Fooable>(): Array<T> { let list ...

Is there a way for me to determine if there are elements in one object array that exist in another object

Is there a method to check if two object arrays have any common elements, and if so, find the intersecting object? Similar to a Contains function. For instance, in the provided example, ProductId3 in Object Array 1 is also present in Object Array 2. I&apo ...

Changing the name of an Angular2 import module

Deciding to improve readability, I opted to rename the @angular module to angular2 and gain a better understanding of how imports function. Prior to making this change, the systemjs.config.js appeared like so: (function(global) { var map = { ...

Is it feasible to set an empty object as the initial default value in the state of a React component?

In my React application with TypeScript, I am using "react": "^17.0.0". Here is how I define the app state: export interface IRoleState { data: API.RoleItem, menus: API.MenuItem, } When I set up the initial state like this: con ...

Enhancing editor.selections in Visual Studio Code Extension

I'm currently developing a vscode extension that involves moving each selection of a multi-selection to the right by one character. The challenge lies in updating the TextEditor.selections array, which stores all current selections in the GUI. When I ...

It appears that Yarn is having trouble properly retrieving all the necessary files for a package

Recently, I encountered a strange issue in our project involving 3 microservices, all using the exceljs library. Two of the microservices successfully download all necessary files for this package through yarn. However, the third microservice is missing ...

Tips for testing SSM's GetParameter with aws-sdk-client-mock in typescript

I'm looking to create a test case for the SSM GetParameterCommand request in TypeScript. Here is my code snippet: const region = "us-east-1" const awsSSMClient = new SSMClient({ region }) export async function fetchParam(parameterName: string, decry ...

The visibility of the button is dependent on refreshing the page with the F5

I'm currently experiencing an issue with my code. The backoffice button is not showing up when I log in as an admin, unless I refresh the page by pressing F5. useEffect(() => { // Ensure window.FB and window.FB.XFBML are defined before calling ...

Tips for successfully importing $lib in SvelteKit without encountering any TypeScript errors

Is there a way to import a $lib into my svelte project without encountering typescript errors in vscode? The project is building and running smoothly. import ThemeSwitch from '$lib/ThemeSwitch/ThemeSwitch.svelte'; The error message says "Canno ...

Send a string to directive via HTML

Trying to implement a "clipboard" directive following this example. In my case, I need to dynamically compute the string to be copied to the clipboard. The goal is to pass the output of a function that generates the string to the directive. Currently, I ...

Is it possible to identify and differentiate objects based on their interface types in JavaScript/TypeScript?

Incorporating a library that defines the following interfaces: LocalUser { data { value: LocalDataValue }, ...various other methods etc... } RemoteUser { data { value: RemoteDataValue }, ...various other methods etc... } A User is then ...