Lionel Rowe
Lionel Rowe

Reputation: 5926

Type-safe setter-only property in TypeScript

I was surprised to find that the following code compiles fine in TypeScript and only errors at runtime:

class X {
    set writeOnlyProp(value: number) {
        // do some setting stuff
    }
}

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

I know it's possible in newer versions of TS to add a getter that explicitly returns undefined, but that seems like a hack. Is there a better way of typing this? Or perhaps a TSConfig strict* flag that handles it automatically?

Upvotes: 0

Views: 58

Answers (2)

Sonam
Sonam

Reputation: 1

When you attempt to access x.writeOnlyProp.toString(), it results in a runtime error because x.writeOnlyProp is undefined (as there is no getter defined).

Define a Getter: Define a getter that returns undefined or some other default value. This isn't really a hack but a way to ensure the property is defined on the object.

Upvotes: 0

Behemoth
Behemoth

Reputation: 9300

There are issues on Github such as microsoft/TypeScript#58112 and microsoft/TypeScript#30852 addressing that behavior. The canonical issue would probably be microsoft/TypeScript#21759 which is requesting suppport for a writeonly modifier on properties.

Either way this was first considered a breaking change (as mentioned in this comment) but might be worked on in the future since set is now encoded into the declaration files.

As of now, you can use the accessor pair ESLint rule which can be configured to error if a setter is missing a corresponding getter.

Upvotes: 1

Related Questions