When defining a class property in TypeScript, you can make it optional by not providing

Is there a way to make a property on a Class optional without it being undefined?

In the following example, note that the Class constructor takes a type of itself (this is intentional)

class Test {
  foo: number;
  bar: string;
  baz?: string;

  constructor(test: Test) {
    this.foo = test.foo;
    this.bar = test.bar
    this.baz = test.baz || "Default";
  }
}

const first = new Test({foo: 1, bar: "Bob"});

const str = "Some Default String about Bob";

str.replace(first.baz, "New Value");
// Type 'undefined' is not assignable to type 'string | RegExp'.(

I am aware that I can use the ! operator, but would rather avoid it

str.replace(first.baz!, "New Value");

This question seems to address the issue —"class properties can't rely on default values"

Answer №1

From my understanding, you are not looking for the class property to be optional, but rather the constructor parameter to be optional. This can easily be achieved:

interface TestOptions {
  foo: number;
  bar: string;
  baz?: string; // optional
}

class TestClass {
  foo: number;
  bar: string;
  baz: string; // NOTE: not optional!

  constructor ({
    foo,
    bar,
    baz,
  }: TestOptions) {
    this.foo = foo;
    this.bar = bar;
    this.baz = baz ?? "Default";
  }
}

I have utilized the nullish coalescing operator to handle the default value assignment more efficiently. If you prefer a more concise syntax with positional parameters in the constructor, you can achieve that as well:

class Test2 {
  constructor (
    public foo: number,
    public bar: string,
    public baz = "Default",
  ) {}
}

Although there might be slight differences in behavior regarding optional parameters, the end result is quite similar.

Playground

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

Ways to avoid using a specific type in TypeScript

Imagine having a class that wraps around a value like this: class Data<T> { constructor(public val: T){} set(newVal: T) { this.val = newVal; } } const a = new Data('hello'); a.set('world'); // typeof a --> Primitiv ...

Accessing getUserMedia within Internet Explorer 11 or utilizing MediaStream on IE 11

I am attempting to utilize the getUserMedia function in IE 11 with the help of the temasys plugin. However, IE does not support the MediaStream instance returned by getUserMedia. Below is a snippet of my code: import React from 'react' import { ...

How can I trace the origin of a post request sent from a form?

When constructing an HTML form, I typically utilize <form action="/postRoute" method="post"> to submit a post request. However, while examining a form for which I needed the post request URL, I came across the following: <form action="index.cf ...

How to show table cell value in Angular 4 using condition-based logic

I am a beginner in Angular development. Here is the HTML code I am working with: <tr *ngFor="let item of calendarTableSelected; let idx = index"> <span *ngIf="idx === 0"> <td style="width:15%;" *ngFor="let name of item.results" ...

TypeScript is unable to identify import paths

Currently facing an issue with a specific error in my development environment. I am working with React, TypeScript, and node.js using VSCode on a Mac. I can't pinpoint exactly when this error started occurring. Despite the existence of the file route ...

Calculate the total number of table rows added using jQuery

I am seeking help to identify the error in my code. My goal is to count the number of table rows added by the end user and display an alert box if the row count is not equal to 2. Below is my HTML code: <table width="100%" border="0" cellspacing="0" c ...

Issue with JQuery dialog not triggering autocomplete

I have integrated the JQuery 1.7.2 and JQuery-UI 1.8.18 libraries with both http://docs.jquery.com/UI/Dialog and http://docs.jquery.com/UI/Autocomplete. On a standard page load, the autocomplete function works perfectly with a text box in a form. It' ...

What is the best way to organize an Express application that handles both API requests and views?

Currently, I am in the process of developing a small application that will function as both a website and its API. To achieve this, I am utilizing Node, Express, and Webpack. The structure of my directory is organized as follows: >client |>dist ...

Is there a way to search for multiple items using just one search term?

On my app, there is a search bar that currently only looks up data for one specific attribute. For example, if I type in "Hammer," it only searches for Tool names. Now, I need to expand the search functionality to accommodate different types of strings. F ...

Jquery unresponsive in AJAX form output presentation

I recently delved into the world of jquery and AJAX, and while I grasp most concepts, I'm struggling with a small code snippet. On my webpage, there is a summary of articles. Clicking on an article name triggers a popup window with detailed informati ...

Tips for implementing multiple selectors in YUI

Is there a way to use multiple selectors in YUI (YUI 2) similar to jQuery? $('h1, h2, el1, el2, .content, .title').css('color', 'red'); How can I achieve the same in YUI without having to individually add classes using YAHOO ...

Storing JavaScript arrays in CSV format on the server

I am currently facing an issue while trying to save a multidimensional Javascript array as a CSV file on the server. Despite my efforts, the CSV file created does not seem to contain the actual array data, and I am unsure of what is causing this discrepanc ...

Guide on sharing a Vue project with other devices within a network

I'm a complete beginner when it comes to vue.js. After working on a few small projects, I want to make sure I understand how to share a vue project with others at this stage. Typically, I know that running 'npm run serve' in my project dir ...

Can AngularJS Filters be used to convert a number into a string, but not the other way around?

After researching Angular JS filters, I discovered that the number filter is used to format a number as a string. However, there doesn't seem to be a built-in filter for converting a string to a number. In an attempt to solve this issue, here is so ...

Swap out the content within the selected element

Let's imagine we have the following shopping list: export default { data() { return { items: { Apple, Orange, Appricot } } } } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js" ...

Loop through a JSON object to dynamically update the value of a specific key

I have a JSON object with keys and values, where some of the values are empty strings. I want to replace those empty values with the corresponding key name. However, when trying to get the value of a key within the loop, it returns undefined. JSON: "Forg ...

Browse the string on the web browser

Is there a way for me to continuously read and capture a string as it is being written in the browser, retrieving its value every 5 seconds? I need to be able to monitor the changing value while it is being input. In PHP, I have the following code snippet ...

What could be the reason behind my useEffect() not triggering when updating a value in a React context?

How come my useEffect hook doesn't trigger when I update a dependency that involves a React context? In my project, the context is used within a wizard to gather user data and then process it on the final step. I am able to update the "Person" fields ...

Generate pre-set components using fundamental building blocks

Can I predefine some props for components? In my Vuetify example, let's say I want to customize the v-btn component with specific props. This custom implementation would act as a child component while still providing all the functionalities of the par ...

Here is a unique rewrite: "Strategies for effectively passing the data variable in the geturldata function within Vue.js on the HTML side vary

How can I properly pass a variable in the getdataurl function in Vue.js? I need help with passing a variable in getdataurl function in Vue.js. Please provide a clear explanation and include as much detail as possible. I have tried doing some background r ...