I have a function that accepts multiple boolean flags, each requiring different arguments to be passed.
Here is a simplified version:
enum FLAGS {
A = 'a',
B = 'b',
C = 'c'
}
interface ARelatedArgs {
aBool: boolean
aString: string
}
interface BRelatedArgs {
(bEvt: any): void
bBool: boolean
}
interface CRelatedArgs {
(cEvt: any): string
cString: string
}
interface MyFunctionArgs {
flags: Partial<Record<FLAGS, boolean>>
// other properties based on flags
}
function myFunction(args: MyFunctionArgs) {
// do something
}
Now I want to have type inference based on these calling patterns:
// First call to my function
myFunction({
flags: { [FLAGS.A]: true }
// all ARelatedArgs
})
// Second call to my function
myFunction({
flags: { [FLAGS.A]: true, [FLAGS.B]: true }
// all ARelatedArgs
// + all BRelatedArgs
})
// Last call to my function
myFunction({
flags: { [FLAGS.A]: true, [FLAGS.B]: true, [FLAGS.C]: true }
// all ARelatedArgs
// + all BRelatedArgs
// + all CRelatedArgs
})
I am looking for TypeScript to check and infer argument types based on the passed flags. I'm interested in having IntelliSense assist with this when passing multiple flags rather than just one. Can TypeScript provide this functionality?
I understand that I am requesting runtime checking from TypeScript. How can I achieve this?
I envision MyFunctionArgs
to be structured like this:
interface MyFunctionArgs {
flags: Partial<Record<FLAGS, boolean>>
...(FLAGS.A in flags && ARelatedArgs),
...(FLAGS.B in flags && BRelatedArgs),
...(FLAGS.C in flags && CRelatedArgs),
}