I am struggling to differentiate between members of a discriminated union made up of function types. Take a look at the following example:
type _NumFunc = (n: number) => string;
type _StrFunc = (s: string) => string;
interface NumFunc extends _NumFunc { __type: 'NumFunc'; }
interface StrFunc extends _StrFunc { __type: 'StrFunc'; }
type Func = NumFunc | StrFunc;
let myNumFunc = ((n: number) => `Hello x${n}!`) as NumFunc;
let myStrFunc = ((s: string) => `Hello, ${s}!`) as StrFunc;
let funcGen = (n: number): Func => n % 2 == 0 ? myNumFunc : myStrFunc;
for (let i = 0; i < 2; i++)
{
let func = funcGen(i);
switch (func.__type)
{
case 'NumFunc':
console.log(func(3));
break;
case 'StrFunc':
console.log(func('World!'));
break;
default:
console.error(func);
console.error('How did this happen?');
break;
}
}
I anticipate that the program should output:
Hello x3!
Hello, World!
However, when you execute this code, you will notice that the default case is triggered for each iteration. Simply logging func
will display the function object, but trying to access __type
on the object results in an error indicating that the type of func
is never
. Why does this method not work, and is there an alternative approach to utilize discriminated unions of function types?