I'm afraid that you're going to have to use a type assertion to avoid code duplication here. TypeScript's type system just doesn't have good support for these "correlated record types" or any manipulation that relies on the interaction of two union-typed values where the unions are not independent.
You've already arrived at the redundant-code-in-switch
-statement workaround; here's the unsafe-assertion workaround:
function assertNarrowFunction<F extends (arg: any) => any>(f: F) {
return f as (arg: Parameters<F>[0]) => ReturnType<F>; // assert
}
That takes a function of a union type like ((a: string)=>number) | ((a: number)=>boolean)
and unsafely narrows it to a function which takes the union of its parameter types and returns the union of its return type, like ((a: string | number) => string | number)
. This is unsafe because a function of the former union type could be something like const f = Math.random()<0.5 ? ((a: string)=>a.length) : ((a: number)=>number.toFixed())
, which definitely does not match ((a: string | number) => string | number)
. I can't safely call f(5)
because maybe f
is the string-length function.
Anyway, you can use this unsafe narrowing on renderFn
to silence the error:
function renderFnAssertion(field: FormField) {
const renderFn = assertNarrowFunction(fieldMapping[field.type]);
renderFn(field.data); // okay
}
You've lied to the compiler a bit about the type of renderFn
... not so much that it will accept any old argument (e.g., renderFn(123)
will fail as desired), but enough that it would allow this:
function badRenderFn(field1: FormField, field2: FormField) {
const renderFn1 = assertNarrowFunction(fieldMapping[field1.type]);
renderFn1(field2.data); // no error!!! ooops
}
So you have to be careful.
Okay, hope that helps; good luck!
Link to code
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…