My map is packed with various types of values (strings, objects, etc.) assigned to different types of keys (strings, classes, etc.).
Whenever the key is a class, the corresponding value is always an instance of that class.
I attempted to create a function that can properly type its return value when it has all information about it, but there seems to be an issue when the class constructor requires parameters:
const map = new Map();
function test<T>(key: new (...args: any[]) => T): T;
function test<T>(key: unknown): T
function test(key: unknown) {
return map.get(key);
}
// testing begins here
class A {}
class B {
constructor(public foo: string) {}
}
const aaa = test(A) //< Correctly typed as `A`
const bbb = test(B) //< Incorrectly typed as `unknown`
const ccc = test('C') //< Correctly typed as `unknown`
const ddd = test<string>('D') //< Correctly typed as `string`
The class B
does not appear to be recognized by the first function overload. However, what baffles me is that if I eliminate the second function overload, then b
is correctly identified as B
(although using the function with anything other than a class results in failure). So why isn't B
acknowledged as a class in the previous scenario?