Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generic Union type, Value or Function in TypeScript

How to safely get the value from generic type V | ((k: K) => V)?

It’s a common case to provide default value as a value or as result of a function.

Playground

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Hash<K, V> {
  get_or_default(k: K, dflt: V | ((k: K) => V)): V {
    return (typeof dflt == 'function' ? dflt(k) : dflt
  }
}

The problem is this dflt(k) it refuses to compile because it:

This expression is not callable.
  Not all constituents of type '((k: K) => V) | (V & Function)' are callable.
    Type 'V & Function' has no call signatures.(2349)

P.S. Why dflt: Exclude<V, Function> | ((k: K) => V) doesn’t work?

>Solution :

Use instanceof instead of typeof.

class Hash<K, V> {
  get_or_default(k: K, dflt: V | ((k: K) => V)): V {
    return (dflt instanceof Function) ? dflt(k) : dflt;
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading