Skip to content

Commit b3d618f

Browse files
author
lukaw3d
committed
Make cn type stricter
1 parent 5de08b8 commit b3d618f

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/components/alert/index.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export const Alert: FC<AlertProps> = ({ className, title, variant = 'info', stic
5353
>
5454
<Icon
5555
className={cn('w-4 h-4 min-w-4 min-h-4', {
56-
'mt-0.5': title,
56+
'mt-0.5': !!title,
5757
'-mt-1': !title && sticky,
5858
})}
5959
/>

src/lib/utils.ts

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,30 @@
1-
import { clsx, type ClassValue } from 'clsx'
1+
import { clsx } from 'clsx'
22
import { twMerge } from 'tailwind-merge'
33

4-
export function cn(...inputs: ClassValue[]) {
4+
// Stricter than `ClassValue` from clsx
5+
export type ClassValueStrict = ClassArrayStrict | ClassDictionaryStrict | string | null | false | undefined
6+
export type ClassDictionaryStrict = Record<string, boolean | null | undefined>
7+
export type ClassArrayStrict = ClassValueStrict[]
8+
9+
export function cn(...inputs: ClassValueStrict[]) {
510
return twMerge(clsx(inputs))
611
}
12+
13+
{
14+
// Type-only test:
15+
const condition = false
16+
// `clsx` is not strict enough
17+
clsx('class1', 2, condition && 'no3', { class4: true, class5: 5, class6: [{ why: '?' }] })
18+
// @ts-expect-error `cn` should be stricter and disallow this
19+
cn('class1', 2, condition && 'no3', { class4: true, class5: 5, class6: [{ why: '?' }] })
20+
// @ts-expect-error `cn` should be stricter and disallow this
21+
cn('class1', 2)
22+
// @ts-expect-error `cn` should be stricter and disallow this
23+
cn('class1', true, 'class3')
24+
// @ts-expect-error `cn` should be stricter and disallow this
25+
cn('class1', { class5: 5 })
26+
// @ts-expect-error `cn` should be stricter and disallow this
27+
cn('class1', { class6: [{ why: '?' }] })
28+
// Valid
29+
cn('class1', condition && 'no3', { class4: true })
30+
}

0 commit comments

Comments
 (0)