typescript create object with some properties using object literal

Is there a way to initialize an instance of a class with an object literal that doesn't contain all the elements in the class, but those present are part of the class?

class Example{
    text:string;
    number:number;

    displayResult(){return this.text + this.number;}
}
let example=new Example;

example={text:"hello",number:12};   // error, displayResult() is missing in the object literal

What is the correct method for assigning values while still utilizing TypeScript's validations?

example=Object.assign(example,{text:"hello",numberrr:12});

This approach could work, however it bypasses validation for input fields - notice 'numberrr' which is incorrect but still passed through.

Answer №1

To create an instance of a class from an object literal, use the syntax new ClassName()

A convenient approach is to include a constructor that accepts a Partial<T>

class ExampleClass{
    text:string;
    numberValue:number;
    constructor(obj: Partial<ExampleClass>) {
        Object.assign(this, obj);
    }
    
    displayResult() { return this.text + this.numberValue; }
}

let exampleInstance = new ExampleClass({text:"welcome", numberValue:7});

This constructor allows for field validations as needed.

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

Having trouble accessing @ViewChildren from the parent component

I've been facing an issue while attempting to control the child instances of a component and I can't seem to bypass this particular error. I've been referring to solutions provided on this specific thread. The main component Sequence houses ...

Using Snap SVG in a React application with Next.js and TypeScript

Query I have been attempting to incorporate SnapSVG into my React project, but I am encountering difficulties getting it to function properly from the outset. Can someone provide assistance with the correct configurations? I do not have much experience wi ...

Encountering Typescript issues while trying to access @angular/core packages

Recently, I made an update to my Ionic app from Angular 7 to Angular 8, and an odd error popped up: https://i.sstatic.net/icZOb.png The issue lies in the fact that I am unable to access any of the standard classes stored in the @angular/core module. This ...

Advantages of using ConfigService instead of dotenv

What are the benefits and drawbacks of utilizing @NestJS/Config compared to using dotenv for retrieving environment variables? Although I can create a class to manage all envvars in both scenarios, is it necessary? I am aware that @NestJS/Config relies on ...

Failed to retrieve values from array following the addition of a new element

Does anyone have a solution for this problem? I recently added an element to my array using the push function, but when I tried to access the element at position 3, it wasn't defined properly processInput(inputValue: any): void { this.numOfIma ...

Error encountered: NextJs could not find the specified module, which includes Typescript and SCSS

I am in the process of migrating a Next.js application from .js to .ts and incorporating ScSS. The first error I encounter is during 'npm run dev'. However, when I try 'npm run build', different issues arise that do not seem related to ...

Only object types can be used to create rest types. Error: ts(2700)

As I work on developing a custom input component for my project, I am encountering an issue unlike the smooth creation of the custom button component: Button Component (smooth operation) export type ButtonProps = { color: 'default' | 'pr ...

Input value not being displayed in one-way binding

I have a challenge in binding the input value (within a foreach loop) in the HTML section of my component to a function: <input [ngModel]="getStepParameterValue(parameter, testCaseStep)" required /> ... // Retrieving the previously saved v ...

Encountering a "ReferenceError: global is not defined" in Angular 8 while attempting to establish a connection between my client application and Ethereum blockchain

I'm trying to configure my web3 provider using an injection token called web3.ts. The token is imported in the app.component.ts file and utilized within the async ngOnInit() method. I've attempted various solutions such as: Medium Tutorial ...

Finding the solution to the perplexing issue with Generic in TypeScript

I recently encountered a TypeScript function that utilizes Generics. function task<T>(builder: (props: { propsA: number }, option: T) => void) { return { run: (option: T) => {}, } } However, when I actually use this function, the Gener ...

Develop a TypeScript utility function for Prisma

Having trouble inferring the correct type for my utility function: function customUtilityFunction< P, R, A extends unknown[] >( prismaArgs /* Make "where" field optional as it is already defined inside findUnique method below */, fn: ( pris ...

Using Angular's ngForm within an ng-template

Within my ng-template, there is a form displayed in a modal. .ts @ViewChild('newControlForm', {static: false}) public newControlForm: NgForm; .html <ng-template> <form role="form" #newControlForm="ngForm"> </form> </ng ...

The closeOnClickOutside feature seems to be malfunctioning in the angular-2-dropdown-multiselect plugin

I'm currently using 2 angular-2-dropdown-multiselect dropdowns within a bootstarp mega div. The issue I'm facing is that when I click on the dropdown, it opens fine. However, when I click outside of the dropdown, it doesn't close as expected ...

Currying disrupts the inference of argument types as the argument list is divided in half, leading to confusion

One of my favorite functions transforms an object into a select option with ease. It's written like this: type OptionValue = string; type OptionLabel = string; export type Option<V extends OptionValue = OptionValue, L extends OptionLabel = OptionL ...

What is preventing the combination of brand enums in Typescript 3?

Utilizing brand enums for nominal typing in TypeScript 3 has been a challenge for me. The code snippet below demonstrates the issue: export enum WidgetIdBrand {} export type WidgetId = WidgetIdBrand & string; const id:WidgetId = '123' as Wi ...

Tips for sorting queries within a collection view in Mongoose:

I am working with Mongoose and creating a view on a collection. NewSchema.createCollection({ viewOn: originalModel.collection.collectionName, pipeline: [ { $project: keep.reduce((a, v) => ({ ...a, [v]: 1 }), {}), }, ], ...

Why do my messages from BehaviorSubject get duplicated every time a new message is received?

Currently, I am using BehaviorSubject to receive data and also utilizing websockets, although the websocket functionality is not relevant at this moment. The main issue I am facing is why I keep receiving duplicated messages from BehaviorSubject. When exa ...

Is there a way to incorporate timeouts when waiting for a response in Axios using Typescript?

Can someone assist me in adjusting my approach to waiting for an axios response? I'm currently sending a request to a WebService and need to wait for the response before capturing the return and calling another method. I attempted to utilize async/aw ...

Storing the value of e.currentTarget in a TypeScript variable with a fixed data type

Within my interface, MyObject.type is designated as a type of (constant): 'orange' | 'apple'. However, when attempting to execute: MyObject.type = e.currentTarget.value in the onChange method, an error arises since it could potentially ...

Ways to access configuration settings from a config.ts file during program execution

The contents of my config.ts file are shown below: import someConfig from './someConfigModel'; const config = { token: process.env.API_TOKEN, projectId: 'sample', buildId: process.env.BUILD_ID, }; export default config as someCo ...