#Overload class method return type

6 messages · Page 1 of 1 (latest)

lone groveBOT
#
m.a.t.t.t#0

Preview:ts class X { foo(xyz?: false): number foo(xyz: true): string { return xyz === true ? "abc" : 10 } }

dawn wharf
#

Is it possible to make this work?

molten trout
#

The implementation needs to handle the most generic case. Something like this:

class X {
  foo(xyz?: false): number
  foo(xyz: true): string
  foo(xyz?: boolean): string | number {
    return xyz === true ? 'abc' : 10
  }
}
dawn wharf
#

Oh cool, thanks Evan. It looks like the compiler won't check for correctness against overloads though, is that right? e.g. if I change the 10 to "10" it won't check the false branch is correctly returning a number

vague fox
#

yes, overloads aren't checked

dawn wharf
#

thanks 🙂