I have a map that contains different types (string, objects, …) of values, under different types (string, Class, …) of key.
When the key is a class, the value is always an instance of that class.
I’ve tried to write a function that correctly type its return value when known, but it doesn’t work when the class constructor takes 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);
}
// test begin 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`
So the class B
doesn’t seem to be recognized by the first function overloading, but what I cannot understand is that if I remove the second function overload, then b
is correctly typed as B
(but then calling the function with anything else than a class fails). So why isn’t B
recognized as a class in the previous situation ?