Ensuring Type Safety with Setter-Only Properties in TypeScript

I found it quite surprising that this piece of code compiles without any issues in TypeScript, but throws an error at runtime:

class Y {
    set writeOnlyProp(value: number) {
        // perform some actions here
    }
}

const y = new Y()
// runtime error: Cannot read properties of undefined
console.log(y.writeOnlyProp.toString())

I am aware that in newer versions of TS, it is possible to add a getter that explicitly returns undefined, but that solution feels like a workaround. Is there a more appropriate way to type this? Or maybe a TSConfig strict* flag that can handle it automatically?

Answer №1

GitHub has identified several issues, like microsoft/TypeScript#58112 and microsoft/TypeScript#30852, that discuss certain behaviors. A key problem is highlighted in microsoft/TypeScript#21759, requesting support for a writeonly modifier on properties.

Initially seen as a breaking change (as noted in this comment), it may be addressed in the future now that set is included in the declaration files.

Currently, you have the option to utilize the accessor pair ESLint rule, which can be set to flag errors if a setter lacks a corresponding getter.

Answer №2

Trying to retrieve the value of x.writeOnlyProp.toString() will trigger a runtime error, as x.writeOnlyProp is not defined due to the absence of a getter.

Create a Getter: Implement a getter that returns either undefined or a default value. This approach ensures that the property exists on the object, serving as a proactive measure rather than a workaround.

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

TS1086: Attempting to declare an accessor within an ambient context is not allowed

While using Angular, I encountered the error TS1086: An accessor cannot be declared in an ambient context. when using Javascript getters and setters in this Abstract Typescript class. Here is the code snippet causing the issue: /** * The current id ...

The issue of a malfunctioning react TypeScript map when used in conjunction with useContext

I am attempting to retrieve data from the TVMaze API using React, TypeScript, and useContext. Although I can display the data, the useContext does not update with the return value, so when I use the map function, nothing is displayed. Any advice on how to ...

Enhancing IntelliSense to recognize exports specified in package.json

I have a package.json file where I define various scripts to be exported using the exports field. "exports": { ".": { "default": "./dist/main.es.js", "require": "./dist/main.cjs.js", ...

Threading in Node.js for Optimized Performance

Having trouble making axios calls in worker threads Hello, I'm working on a Node.js application and attempting to utilize worker threads for one specific task. Within the worker thread, I need to make an axios call, but I keep encountering an error w ...

Troubles with Typescript typings when including an empty object in an array with specific typings

, I am facing a dilemma with displaying houses in a cart. Each house has an image, but since they load asynchronously, I need to show empty cards until the data is fetched. Initially, I added empty objects to the array representing the houses, which worked ...

Struggling with transitioning from TypeScript to React when implementing react-data-grid 7.0.0

I'm trying to add drag and drop functionality to my React project using react-data-grid, but I keep encountering a "TypeError: Object(...) is not a function" error. I have a TypeScript version of the file in the sandbox as a reference, but when I try ...

Create a collection of values and assign it to a form control in Ionic 2

How can I set default values for ion-select with multiple choices using a reactive form in Angular? FormA:FormGroup; this.FormA = this.formBuilder.group({ toppings:['',validators.required] }); <form [formGroup]="FormA"> <i ...

Unable to transfer an object into a component due to a subscribe restriction

I have encountered an issue: I am making a post request to save an object in the database. The request takes JSON input with the values of the object to be saved. After saving the object in the database, I need my servlet to return the saved object so that ...

Sending information from a component inside a router-outlet to a higher-level "Parent" component in Angular 2

Is there a way to transfer data from a component embedded within a router-outlet tag in a "parent" component's HTML template back to the parent component? ...

A data type representing a specific category rather than a specific object

My job involves working with Sequalize models, which are essentially classes. Upon registration, these models are populated with some data that needs to be stored. To accomplish this, I store them in a list. However, when retrieving a model into a variab ...

Using asynchronous data in Angular 2 animations

Currently, I have developed a component that fetches a dataset of skills from my database. Each skill in the dataset contains a title and a percentage value. My objective is to set the initial width value of each div to 0% and then dynamically adjust it t ...

You must add the module-alias/register to each file in order to use path aliases in

I am currently utilizing typescript v3.6.4 and have the following snippet in my tsconfig.json: "compilerOptions": { "moduleResolution": "node", "baseUrl": "./src", "paths": { "@config/*": ["config/*"], "@config": ["config"], ...

What is the method for transmitting a URL API from an ASP.NET Core server to my Angular 2 single application?

Is there a way to securely share the url of the web api, which is hosted on a different server with a different domain, from my asp net core server to my client angular2? Currently, I am storing my settings in a typescript config file within my angular2 ap ...

The occurrence of "xyz" member in the code is inferred to have an unspecified "any" type, resulting in an error when utilizing react with typescript

I'm currently utilizing the React useForm hook along with typescript for validation. I have set up setError, clearError, and created specific types for it. However, I've encountered an error stating "Member 'xyz' implicitly has an &apos ...

Put off the assessment of JSX

As I was working with a function that returns JSX to React components, I realized the need to include some state variables of the components in the JSX as well. Each component might require changing the JSX or its values. Take a look at the code snippet be ...

Issue accessing member value in inherited class constructor in Typescript

My situation involves a class named A, with another class named B that is inherited from it. class A { constructor(){ this.init(); } init(){} } class B extends A { private myMember = {value:1}; constructor(){ super(); ...

Having trouble retrieving image information within the Asp.net core controller

I am facing an issue trying to store image details in the database through Angular and ASP.NET Core. I am unable to retrieve the image data sent from Angular in the controller. Although I am able to obtain the image information using the [FromForm] attribu ...

Steps to execute an Angular directory within a project

Click here for imageWhenever I try to run ng serve command from the directory, it doesn't seem to work and just takes me back to the same directory. I'm having trouble running my Angular project. Any suggestions on how to solve this issue? ...

To tally and showcase the existing strings within an array

I am working with an API named teachers that has the following structure: Teachers: [ { "id": "01", "teacherName": "Binky Alderwick", "studentIds": [ "010", "024", "031" ], "totalStudents":"20" }, { "id": " ...

Universal Enum variable

I came up with a function that accepts a specific type of enum value to determine a color to pass as a prop to another function. However, I want the flexibility to throw a different enum at my function. I thought about using a generic type, but TypeScript ...