Issue
I have developed a Typescript package to share types between my backend node firebase cloud functions and frontend React client that accesses them. Provided below are examples of the types:
interface FirstFunctionInput {
x: number
}
interface SecondFunctionInput {
y: string
}
// lists all available functions
enum FirebaseFunction {
FirstFunction = "firstFunction",
SecondFunction = "secondFunction"
}
Currently, I am invoking the functions using the firebase sdk:
firebase.funtions.httpsCallable('firstFunction')({ x: 21 })
.then(result => { ... })
The challenge at hand is:
- There is no assurance that the function 'firstFunction' exists.
- Even if it does, how can one confirm that it accepts a parameter like
{ x: 21 }
.
Thus, I aim to create a utility method using Generics that resolves these issues.
Preferred Solution
Desired API representation is provided in the example below. A scenario where an incorrect input type is passed to the function is outlined, anticipating Typescript to flag an error.
callFirebaseFunction<FirstFunction>({ y: 'foo' })
^----------^
display error here as FirstFunction should accept a FirstFunctionInput
Current Progress (not fully achieved yet)
I have made progress towards this goal with a functioning API, although input parameters must be specified during the call:
callFirebaseFunction<FirstFunctionInput>(
FirebaseFunction.FirstFunction,
{ x: 21 }
)
.then(result => { ... })
This setup is not ideal since the programmer needs knowledge of the input type to specify.
Closing Thoughts
Despite attempting various strategies involving interfaces extension, abstract classes extension, and even the builder pattern, I struggle to consolidate everything. Is such a solution feasible?