What is the best way to convert `{}` to type `T` while keeping the default values intact in TypeScript?

If I have a Product with three properties and their default values, how can I convert or cast an empty object to a Product while maintaining the default values when no value is present?

export class Product {
  Price: number = 20;
  Label: string = "No name";
  Details: string = "no desc";
}
let laptop = { Label: 'Laptop' } as Product;
//I want to transform this laptop object to {Label:'Laptop', Price:20, Details:'no desc'}

Answer №1

Type casting alone does not allow for achieving this functionality. When you cast an object as Product, you are essentially telling the compiler, "Treat this as a Product even though it may not possess all the attributes of a Product".

If default values are needed, a constructor must be added to the class, like so:

export class Product {
  price: number;
  label: string;
  details: string;

  constructor(obj: {price?: number, label?: string, details?: string}) {
    this.price = obj.price || 20;
    this.label = obj.label || "No name";
    this.details = obj.details || "No description";
  }
}

This way, passing a partial configuration object will automatically set the other default values.

let laptop = new Product({label: 'Laptop'}); 
// {label: 'Laptop', price: 20, details: 'No description'}

Now, laptop is inherently of type

Product</code without needing explicit casting. </p>

<p>An easier approach to typing your constructor parameter is by using the <code>Partial
type.

type Partial<T> = {
  [P in keyof T]?: T[P];
}

Thus, your constructor parameter would appear as

constructor(obj: Partial<Product>)

To delve deeper into type assertions (or type casting), refer to the 'Type Assertions' section within this article: https://www.typescriptlang.org/docs/handbook/basic-types.html.

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

Updating the image source attribute using Vue.js with TypeScript

Let's discuss an issue with the img tag: <img @error="replaceByDefaultImage" :src="urls.photos_base_url_small.jpg'"/> The replaceByDefaultImage function is defined as follows: replaceByDefaultImage(e: HTMLImageElement) ...

Developing with intricate JSON data through HTTP requests in Angular application (MEAN STACK)

Currently, I am facing a challenge while working on my project which involves processing "large" JSON files. These files are fetched from an online MongoDB (Mongo Atlas) and accessed through a simple node JavaScript REST API. The complexity of the JSON dat ...

What is the best way to retrieve a string from a URL?

Is there a way to extract only a specific string from a URL provided by an API? For instance: I'm interested in extracting only: photo_xxx-xxx-xxx.png Any suggestions on how to split the URL starting at photo and ending at png? ...

Error in Typescript: The argument 'T' cannot be assigned to the parameter of type 'number'

Could someone help me diagnose the typescript error in this code snippet? public sortList<T>(data: T[], key: string, action: boolean): Observable<T[]> { const outputData: T[] = data.sort((a, b) => { if (isNaN(a) && isNaN(b)) ...

Angular: How can the dropdown arrow in 'ng-select' be eliminated?

Is there a way to hide the dropdown arrow in an 'ng-select' element in Angular? <div class="col-md-6"> <ng-select id="selectServiceType" [items]="clientServiceTypes$ | async" pl ...

How to effectively manage radio buttons in Angular 6

Here are some questions I have listed below. public QandAList = [ { question:{ id: "Q1", query:"What is the capital of France?" }, options:[ { id: "opt1", text: "Paris" }, ...

Arrange information into sections

This Angular code is used to format text into profile page as blocks of data: <div class="element-box"> <div class="details-wrapper"> <p><b class="label">Remote IP</b>{{apiattempt.remote_ip}}</p> <p>< ...

Using $gte and $lt to search within a range in mongoDB can be tricky when dealing with data types in typescript

Whenever I try to search by range of dates using $gte and $lt, I encounter issues with types. The types for my model are as follows: export interface IOneStoreCa { magId: number, caTtc?: number, marge?: number, } export interface ICa { _id: string ...

Ensure that Template.fromStack() includes resources with the specified logical identifiers

Currently, I am overhauling a CDK stack in TypeScript that has reached the resource limit. Given that it includes stateful resources, I need to ensure that the revamped stack points to the same resources and not new ones that could lead to unfavorable resu ...

Pipe translation is not functioning correctly within the sub-module

I'm currently working on a project where I am utilizing Angular 8 and ngx-translate for translation purposes. Everything was running smoothly after importing the necessary code in app.module.ts to set up the translate service. However, when I decided ...

Is it not correct that a variable is being utilized before it has been assigned in Typescript?

What makes the code below invalid in strict mode? let x: string[]; if (Math.random() > .5){ x = ['x']; } //TS2454: x possible undefined. Yeah, I know? return x?.map(v => v); Yes, it is acknowledged that x could potentially be undefined. H ...

Unable to activate nb-checkbox from Nebular theme in Angular due to unspecified issue

I recently started using the Nebular theme and encountered an issue with a checkbox that isn't functioning properly. HTML <nb-checkbox [value]="checked" (change)="toggle($event)"></nb-checkbox> TypeScript toggle(checked: any) { ...

What is the most efficient way to check for the presence and truthiness of a nested boolean in Node.js?

There are instances where I must verify the deeply nested boolean value of an object to determine its existence and whether it is set to true or false. For instance, I need to ascertain if payload.options.save is assigned a value of false, yet I am uncert ...

What is the process for accessing my PayPal Sandbox account?

I'm having trouble logging into my SandBox Account since they updated the menu. The old steps mentioned in this post Can't login to paypal sandbox no longer seem to work. Could someone please provide me with detailed, step-by-step instructions o ...

How can a border be applied to a table created with React components?

I have been utilizing the following react component from https://www.npmjs.com/package/react-sticky-table Is there a method to incorporate a border around this component? const Row = require("react-sticky-table").Row; <Row style={{ border: 3, borderco ...

Since transitioning my project from Angular 7.2 to Angular 8, I noticed a significant threefold increase in compile time. How can I go about resolving this issue

After upgrading my project to Angular 8, I noticed a significant increase in compile time without encountering any errors during the upgrade process. Is there a way to restore the previous compile time efficiency? **Update: A bug has been identified as th ...

The quirk of Angular 2 routing when refreshing the page

Being completely new to Angular 2, I find myself facing a routing dilemma that I can't seem to wrap my head around. @Component({ selector: 'app', templateUrl: 'app/app.template.html', directives: [ROUTER_DIRECTIVES] }) ...

Currently, I am collaborating on an e-commerce endeavor utilizing TypeScript and sanity.io, encountering an issue along the way

Encountering an Uncaught TypeError message: Cannot read properties of undefined (reading '_ref'). While attempting to utilize code for displaying API content on a webpage, what might be causing this issue and how can it be resolved to successful ...

Make sure to include '@mui/system' in the list of dependencies for the project

After installing MUI v5.4 in my create react app typescript project, I encountered an issue while trying to import import { createTheme } from '@mui/system'; where eslint kept displaying the error message: '@mui/system' should be liste ...

Trigger the React useEffect only when the inputed string matches the previous one

Currently, I am in the process of creating my own custom useFetch hook. export const useFetch = <T extends unknown>( url: string, options?: RequestInit ) => { const [loading, setLoading] = useState(false); const [error, setError] = ...