Within my code, I am working with an "options" tuple [string, function]
. This tuple provides a string
that identifies a specific check and a function
on which that check is to be performed. It is important to note that the check to be executed must be instructed through the accompanying string, as there is no way to determine it solely from an analysis of the function itself.
// tsconfig.json
// {"compilerOptions": {"noImplicitAny": true}};
// Types and interfaces
interface f1_sig { (x:string): string }
interface f2_sig { (x:number): number }
interface f1Chk_sig { (f1:f1_sig): boolean }
interface f2Chk_sig { (f2:f2_sig): boolean }
type options_type =
['f1', f1_sig] |
['f2', f2_sig] ;
interface optionsDictionary_indexer {
f1: f1Chk_sig;
f2: f2Chk_sig;
}
// Implementations
// Functions and checks defined
const f1: f1_sig = x => x;
const f2: f2_sig = x => x;
const f1Chk: f1Chk_sig = f => f('0')?true:false;
const f2Chk: f2Chk_sig = f => f( 0 )?true:false;
const optionsDictionary: optionsDictionary_indexer = {
f1: f1Chk,
f2: f2Chk
};
// Two alternative implementations that yield Type errors
// Alternative 1
const optionsExtractor_1:
(options: options_type) => boolean
=
options =>
optionsDictionary[options[0]](options[1])
// Type error: 'f1Chk | f2Chk' has no compatible call signatures
// Alternative 2
const optionsExtractor_2:
(options: options_type) => boolean
=
options =>
options[0]==='f1' ? f1Chk(options[1]) :
options[0]==='f2' ? f2Chk(options[1]) : false;
// Another type error: Argument of type 'f1Chk | f2Chk' is not assignable to parameter of type f2_sig
I am encountering compatibility errors with TypeScript, indicating a mismatch between the types of the checks and functions being checked. How can I resolve this issue? If my current implementation is correct, is there a straightforward solution to prevent TypeScript from raising concerns about calling f1Chk
with f2
, or f2Chk
with f1
?