Home > Net >  How to write a a setter for an optional propery in TypeScript which only allows to set a non-empty v
How to write a a setter for an optional propery in TypeScript which only allows to set a non-empty v

Time:03-18

I'm trying to make an optional property in a TS class and create a setter and a getter for it. It is implied that the property can only be set once, so I'm trying to do something like this:

private _signer?: Signer
get signer(): Signer | undefined { return this._signer }
set signer(signer: Signer) {
    if(!this.validateSignerSecret(signer)) throw Error("Invalid signer, won't set")
    if(!this.signer) {
        this._signer = signer;
        return;
    }
    if(JSON.stringify(this.signer) !== JSON.stringify(secret)) throw Error("Another signer is set already, won't update")
}

However, TS copmlains that

The return type of a 'get' accessor must be assignable to its 'set' accessor type Type 'undefined' is not assignable to type 'Signer'

I can change this to

set signer(signer: Signer | undefined) {

but it's not what I really need: I'd like to only allow to set a non-empty Signer while the getter can return undefined.

Can I somehow keep the prop optional and allow to set only non-empty one?

CodePudding user response:

The other answers explain the state of the compiler restrictions. Here is how you can accomplish your goal:

You can use a @ts-ignore or @ts-expect-error comment directive to suppress the compiler restriction and create the types that you want:

TS Playground

declare const s: Signer;

declare class C {
  private _signer?: Signer
  // @ts-expect-error
  get signer (): Signer | undefined;
  set signer (signer: Signer);
}

const c = new C();

c.signer; // Signer | undefined;
c.signer = s; // ok

c.signer = undefined; /*            
  • Related