Home > Mobile >  Can my Typescript class have a typeguard method asserting a property is not null?
Can my Typescript class have a typeguard method asserting a property is not null?

Time:02-02

Say I have a class that has a property that might be null or undefined:

class Pizza {
  constructor(
    public name:    string,
    public cheese?: string
  ) {}

  get hasCheese(): boolean {
    return !!this.cheese
  }
}

Now I want to operate on that possibly-null property downstream:

function eat(cheese: string) { ... }

function enjoy(pizza: Pizza) {
  return pizza.hasCheese && eat(pizza.cheese!)
}

(Obviously in this trivial case, hasCheese is silly and I can just test pizza.cheese directly; my real case is more complicated.)

Is there a way I can write a typeguard on Pizza#hasCheese here so that Typescript will recognize downstream that pizza.cheese is not null (so I don't have to use the ! assertion)? I.e.,

class Pizza {
  ...
  get hasCheese(): boolean & this is {cheese: string} { // <- doesn't work
    return !!this.cheese
  }
}

function enjoy(pizza: Pizza) {
  return pizza.hasCheese && eat(pizza.cheese) // <- no ! operator
}

If pizza.hasCheese can't work, what about a hasCheese() method instead of a getter?

class Pizza {
  ...
  hasCheese(): boolean & this is {cheese: string} {
    return !!this.cheese
  }
}

CodePudding user response:

TypeScript does not currently support annotating property getters as user-defined type guards. There's an open feature request for such support at microsoft/TypeScript#43368. It's marked as "awaiting more feedback", so if you want to see this implemented it wouldn't hurt to give it a

  • Related