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

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;
  }
}

Leave a Reply