Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Dev-Dipesh opened this issue Apr 17, 2024 · 0 comments

Comments

@Dev-Dipesh
Copy link

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());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant