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

fix: use StringMap type for better type safety in utility functions #3220

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/late-buttons-fail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@nextui-org/theme": patch
---

Used `@ts-ignore` to bypass type checking, and used `Object`, leading to potential type problems and limited flexibility. The function now uses the `StringMap` type for better type safety and flexibility.
18 changes: 8 additions & 10 deletions packages/core/theme/src/utils/object.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,37 @@
import flatten from "flat";

export function swapColorValues<T extends Object>(colors: T) {
const swappedColors = {};
type ColorValue = string | boolean;
type ColorMap = Record<string, ColorValue>;

export function swapColorValues<T extends ColorMap>(colors: T) {
const swappedColors: ColorMap = {};
const keys = Object.keys(colors);
const length = keys.length;

for (let i = 0; i < length / 2; i++) {
const key1 = keys[i];
const key2 = keys[length - 1 - i];

// @ts-ignore
swappedColors[key1] = colors[key2];
// @ts-ignore
swappedColors[key2] = colors[key1];
}
if (length % 2 !== 0) {
const middleKey = keys[Math.floor(length / 2)];

// @ts-ignore
swappedColors[middleKey] = colors[middleKey];
}

return swappedColors;
}

export function removeDefaultKeys<T extends Object>(obj: T) {
const newObj = {};
export function removeDefaultKeys<T extends ColorMap>(obj: T): ColorMap {
const newObj: ColorMap = {};
Gaic4o marked this conversation as resolved.
Show resolved Hide resolved

for (const key in obj) {
if (key.endsWith("-DEFAULT")) {
// @ts-ignore
newObj[key.replace("-DEFAULT", "")] = obj[key];
continue;
}
// @ts-ignore
newObj[key] = obj[key];
}

Expand All @@ -52,5 +50,5 @@ export const flattenThemeObject = <TTarget>(obj: TTarget) =>
flatten(obj, {
safe: true,
delimiter: "-",
}) as Object,
}) as ColorMap,
);