ByteGrad / Professional-React-and-Next.js-Course

This repo contains everything you need as a student of the Professional React & Next.js Course by ByteGrad.com
https://bytegrad.com/courses/professional-react-nextjs
111 stars 58 forks source link

Question 🙋‍♂️ Is it a good idea to exclude `undefined` from the `ClassValue` type imported from **clsx** #8

Open Dev-Dipesh opened 3 months ago

Dev-Dipesh commented 3 months ago

Video: 220 Video Title: Cn() Utility Function

Code in the video:

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

  1. 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.
  2. 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.
  3. 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:

  1. 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.
  2. 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.

null still makes far more sense, for example

let optionalClass = someCondition ? 'class3' : null;
cn('class1', optionalClass, 'class2');

On the contrary, for undefined I would rather prefer to see an error

let obj = { className: 'class1' };
cn(obj.missingProperty);  // obj.missingProperty is undefined
function getOptionalClass() {
  // This function might return undefined
}
cn('class1', getOptionalClass());