Typescript's error message here is perfectly descriptive: your function returns something which is assignable to OrderFixture | DecisionFixture
, but not assignable to an arbitrary subtype of it, such as e.g. OrderFixture & HTMLCanvasElement
. If you still aren't sure, consider the following code, in which your function promises to return such a thing; it is clearly not type-safe, but it has no error, because it's only using the return type that your function claims to have.
let canvas = getFixture<'order', OrderFixture & HTMLCanvasElement>('order');
let ctx = canvas.getContext('2d');
Normally, for exactly this reason, you should not have a type parameter which only appears in the return position, because it allows the caller to expect a specific type without passing any argument that allows the function to know what type it is expected to return. In your case, there is no need for the type parameter T
: just make ReturnType<FixtureStore[K]>
the return type of your function directly.
That said, in this case there is something fishy going on that does seem to be Typescript's fault: even splitting up the function's logic and providing type annotations to help the compiler, Typescript still gives an error.
function getFixture<K extends keyof FixtureStore>(entityName: K): ReturnType<FixtureStore[K]> {
let factory: FixtureStore[K] = fixtureStore[entityName];
// error here
let instance: ReturnType<typeof factory> = factory();
return instance;
}}
Playground Link
Logically, Typescript should never complain that the type of factory()
might not be assignable to ReturnType<typeof factory>
, yet here it complains of exactly that. So I think this should be looked at by someone who knows about Typescript's internals, and perhaps raised as a bug on their issue tracker.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…