import clsx, { ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
Here the ClassValue has following types:
type ClassValue = string | number | boolean | ClassArray | ClassDictionary | null | undefined
In my opinion, this feels too relaxed.
QUESTION
Is it a good practice to exclude the type undefined from the ClassValue?
import clsx, { ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
type DefinedClassValue = Exclude<ClassValue, undefined>;
export function cn(...inputs: DefinedClassValue[]) {
return twMerge(clsx(inputs));
}
Some pros and cons I can think of:
Pros
Better Type Safety: By excluding undefined, we ensure that all classes are properly defined. This can help catch errors at compile-time where a class might not be defined as expected.
Cleaner Code: Excluding undefined can lead to cleaner, more predictable code. We won't have to check for undefined values when working with classes, which can simplify our code.
Improved Debugging: If a class is undefined, it can be difficult to trace where the issue is coming from. By ensuring all classes are defined, we can make debugging easier.
Cons:
Potential Breaking Changes: If there are parts of our codebase that rely on ClassValue being undefined, this change could break them. We would need to thoroughly test our codebase to ensure this doesn't happen.
Additional Complexity: While excluding undefined can lead to cleaner code, it also adds a layer of complexity to our type definitions. Developers will need to understand why undefined is excluded and what impact it has on the code.
Video: 220 Video Title: Cn() Utility Function
Code in the video:
Here the
ClassValue
has following types:QUESTION
Is it a good practice to exclude the type
undefined
from theClassValue
?Some pros and cons I can think of:
Pros
Cons:
null
still makes far more sense, for exampleOn the contrary, for undefined I would rather prefer to see an error