Function overload in TypeScript
When working with TypeScript, you may encounter situations where a function needs to handle different types of input while maintaining type safety. This is where function overloading comes into play. Let’s look at a practical example of function overloading, inspired by a code snippet from the Supabase source code .
Example: useIsFeatureEnabled
The useIsFeatureEnabled function is a great example of function overloading. It can handle both an array of features and a single feature, returning appropriate results for each case.
Here’s the overloaded function definition:
function useIsFeatureEnabled<T extends Feature[]>(
features: T
): { [key in FeatureToCamelCase<T[number]>]: boolean }
function useIsFeatureEnabled(features: Feature): boolean
function useIsFeatureEnabled<T extends Feature | Feature[]>(features: T) {
const { profile } = useProfile()
if (Array.isArray(features)) {
return Object.fromEntries(
features.map((feature) => [
featureToCamelCase(feature),
checkFeature(feature, profile?.disabled_features),
])
)
}
return checkFeature(features, profile?.disabled_features)
}
export { useIsFeatureEnabled }
How It Works
Supporting Functions and Types
To understand this better, let’s look at the supporting checkFeature function and the type utility FeatureToCamelCase.
checkFeature Function
The checkFeature function determines if a given feature is enabled or not:
领英推荐
function checkFeature(feature: Feature, features?: Feature[]) {
return !features?.includes(feature) ?? true
}
This function returns true if the feature is not in the disabled features list or if no disabled features are provided.
Do watch the Matt Pocock’s Youtube video explanation about the function overloads in TypeScript.
Conclusion
Function overloading in TypeScript allows you to define multiple ways to call a function with different types of input while ensuring type safety. The useIsFeatureEnabled function from Supabase is an excellent example of this concept in action. It demonstrates how to handle different input types seamlessly, providing both flexibility and strong typing.
About me:
Website: https://ramunarasinga.com/
Email: [email protected]
OSS Tinkerer | Software Engineer @ Turner Little
3 个月1. https://github.com/supabase/supabase/blob/master/apps/studio/hooks/misc/useIsFeatureEnabled.ts#L24 2. Matt Pocock’s Youtube video explanation - https://www.youtube.com/watch?v=Vr1BUFw6dJM