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

Generate HTML elements within an AngularJS directive and establish a click event

Can you show me how to create some DOM elements and add a click event to them using an AngularJS directive? My current approach is as follows: var list = document.createElement("div"); list.classList.add('myList'); for(var i = 0; i < n; i++) ...

Despite using Vue and Vuex with Axios asynchronously, the getters are still returning an empty array

I am encountering an issue with getters that are returning the initial state (an empty array). In my component, I have a method called created that sets the axios call result into the state. created() {this.$store.dispatch("SET_STORIES");}, I am using m ...

Vue.js: Issue with updating list in parent component when using child component

I'm encountering an issue when utilizing a child component, the list fails to update based on a prop that is passed into it. When there are changes in the comments array data, the list does not reflect those updates if it uses the child component < ...

Angular HttpClient does not support cross-domain POST requests, unlike jQuery which does

I am transitioning to Angular 13 and I want to switch from using jQuery.ajax to HttpClient. The jquery code below is currently functional: function asyncAjax(url: any){ return new Promise(function(resolve, reject) { $.ajax({ type: ...

Canvg | Is there a way to customize canvas elements while converting from SVG?

Recently, I encountered an issue with styling SVG graphics dynamically generated from data. The SVG graphic appears like this: To address the problem, I turned to Canvg in hopes of converting the SVG into an image or PDF using a hidden canvas element. How ...

Employing a general-purpose function in a recursive manner

My function that removes properties from an object and returns a new one works fine, but it runs into issues when dealing with nested arrays of objects. How can I tackle this challenge? interface User { id: number; name: string; items?: User[]; } co ...

Issues with Angular displaying filter incorrectly

Whenever a user chooses a tag, I want to show only the posts that have that specific tag. For instance, if a user selects the '#C#' tag, only posts with this tag should be displayed. This is how my system is set up: I have an array of blogs that ...

Update text displayed on radio button selection using jQuery

Is there a way to change the label text on a selected radio button from "Set default" to just "default" using jQuery? I think I need to use the class radio-default as the selector, but I'm not very familiar with jQuery. <div class="radio-default ...

Exploring the world of HTTP PUT requests in Angular 4.0

I have encountered an issue with a function I wrote for sending an http put request to update data. The function is not receiving any data: updateHuman(human: Human) { const url = `${this.url}/${human.id}`; const data = JSON.stringify(human); ...

ng-class expressions are constantly evolving and adapting

Within a div, I am utilizing ng-class="{minifyClass: minifyCheck}". In the controller, I monitor changes in two parameters - $window.outerHeight and $('#eventModal > .modal-dialog').height(). If there are any changes, I trigger the minifyChan ...

Postpone the processing of a message in the Service Bus Queue until a specific time using NodeJS

Despite trying multiple tutorials, I have been unable to achieve the desired result so far. Currently, my setup involves a nodejs app that sends messages to the Service Bus Queue and another nodejs app that continuously polls it. The goal is to schedule a ...

Navigate through a series of div elements using Jquery

I need help figuring out how to make the window scroll between different divs in a sequence. The issue is that my current code only works for one specific div at a time. $('.down_arrow').click(function(e){ $('html, body') ...

CSS: Concealing a separate div

I am working with a parent div in my code that has 2 child divs. I am hoping to find a way to hide the second child when hovering over the first child, using only CSS or JavaScript. Take a look at my Fiddle here <div class="parrent"> <div id ...

Develop and arrange badge components using Material UI

I'm new to material ui and I want to design colored rounded squares with a letter inside placed on a card component, similar to the image below. https://i.stack.imgur.com/fmdi4.png As shown in the example, the colored square with "A" acts as a badge ...

How can you receive a file through AJAX response?

I have a standard Ajax function that I regularly use to call a specific function within my node.js server. This particular function is responsible for retrieving a file (usually in xls format) from the server and streaming it back to the client. Below is ...

The functionality of Intersection Observer causes text to appear over the header

Hey everyone, I've been working on a scrolling animation to make text appear when it's at least 50% visible. So far, I have an animated header with an Onscroll Event and Intersection Observer for the text. It's all working well, except for ...

Dynamic Namespaces in Socket.io is a feature that allows for

I am currently working on implementing multiple namespaces in my app. As I receive route parameters, I dynamically create new namespaces. For example: var nsp = io.of('/'); var className; app.post('/class/:classID',function(req,res){ ...

When resizing an anchor tag with a percentage in CSS, the child image width may not scale accordingly

In short, I have multiple draggable images on a map enclosed in anchor tags (<a><img></a>) to enable keyboard dragging. The original image sizes vary, but they are all too large, so I reduced them to 20% of their original sizes using the ...

In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead? var foundPeopleA = findPeopleA().then(function(result) { var res = [] result.map(function(el) { res.push(getProfileXML(el.sid)); ...

Which is the best choice for a large-scale production app: caret, tilde, or a fixed package.json

I am currently managing a sizeable react application in production and I find myself undecided on whether it is more beneficial to use fixed versions for my packages. Some suggest that using the caret (^) is a safer route, but I worry that this could poten ...