I just joined a pre-existing project, where there are some global variables set by the backend. These globals are defined in an interface:
interface IGlobals {
feature_foo: boolean
feature_bar: boolean
someOtherProp: string
}
const globals: IGlobals = {
feature_foo: true,
feature_bar: false,
someOtherProp: 'hello'
}
My task now is to create a function that checks if a specific feature flag exists within these global variables. I have assumed that any property starting with feature_
will always be a boolean (which is true for our case):
// Use this as: `const isEnabled = useFeature('foo')`
function useFeature(feature: string): boolean {
const featureKey = `feature_${feature}`
if (globals.hasOwnProperty(featureKey)) {
// Assuming globals starting with `feature_` are always booleans
return globals[featureKey as keyof IGlobals] as boolean
}
return false
}
Although it works, I feel like it's somewhat of a workaround.
I find the as boolean
statement particularly bothersome. I used it because otherwise TypeScript would rightly raise concerns that the value could be a boolean or string, which doesn't match the function's return type.
Is there a way to improve this?
I suspect that "lookups" may provide a solution, but I don't fully understand that concept.