Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Actually, it's even simpler: you should just be able to use signature overloading:

  myFunc(x: true): number
  myFunc(x: false): string
The article's assertion that TypeScript can't represent this is quite false.


Alas, no:

    foo.ts:1:10 - error TS2393: Duplicate function implementation.


Like this:

https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABA...

It's a bit of a hack, though - if you incorrectly implement myFunc so that, say, it returns a string even when x is true, it can violate the overloading assertions without any error or warning.


Thanks! If anyone else is playing along, to get this to work with tsc I needed to use "--strict".

Being able to use a function along those lines in a type safe manner is still pretty nifty, even if you can't write it with type safety.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: