Skip to content

Commit

Permalink
fix: 토글 컴포넌트 forwardRef, generic 관련 타입 추론 안 되는 문제 해결
Browse files Browse the repository at this point in the history
  • Loading branch information
ghdtjgus76 committed May 24, 2024
1 parent fe8c161 commit 09aa783
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
26 changes: 17 additions & 9 deletions packages/wow-ui/src/components/Toggle/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,19 @@
import { cva } from "@styled-system/css";
import { Flex, styled } from "@styled-system/jsx";
import type {
ComponentPropsWithoutRef,
ComponentPropsWithRef,
ElementType,
KeyboardEvent,
NamedExoticComponent,
ReactNode,
} from "react";
import { forwardRef, useEffect, useState } from "react";

import type {
AsProps,
PolymorphicComponentProps,
PolymorphicRef,
} from "@/types/Polymorphic";

/**
* @template T 렌더링할 요소 또는 컴포넌트 타입
*
Expand All @@ -25,8 +30,7 @@ import { forwardRef, useEffect, useState } from "react";
* @param {ComponentPropsWithoutRef<T>} rest 렌더링된 요소 또는 컴포넌트에 전달할 추가 props.
* @param {ComponentPropsWithRef<T>["ref"]} ref 렌더링된 요소 또는 컴포넌트에 연결할 ref.
*/
export interface ToggleProps<T extends ElementType> {
as?: T;
export interface ToggleProps<T extends ElementType> extends AsProps<T> {
defaultChecked?: boolean;
isDisabled?: boolean;
isChecked?: boolean;
Expand All @@ -52,8 +56,12 @@ const ToggleIcon = ({
);
};

const Toggle = forwardRef(
<T extends ElementType>(
type ToggleComponent = <T extends ElementType = "button">(
props: ToggleProps<T>
) => ReactNode | null;

const Toggle: ToggleComponent = forwardRef(
<T extends ElementType = "button">(
{
as,
defaultChecked = false,
Expand All @@ -64,8 +72,8 @@ const Toggle = forwardRef(
onKeyDown,
onChange,
...rest
}: ToggleProps<T> & ComponentPropsWithoutRef<T>,
ref: ComponentPropsWithRef<T>["ref"]
}: PolymorphicComponentProps<T, ToggleProps<T>>,
ref: PolymorphicRef<T>
) => {
const [isActive, setIsActive] = useState(() => defaultChecked);

Expand Down Expand Up @@ -178,6 +186,6 @@ const toggle = cva({
},
});

Toggle.displayName = "Toggle";
(Toggle as NamedExoticComponent).displayName = "Toggle";

export default Toggle;
21 changes: 21 additions & 0 deletions packages/wow-ui/src/types/Polymorphic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type {
ComponentPropsWithoutRef,
ComponentPropsWithRef,
ElementType,
} from "react";

export interface AsProps<T extends ElementType> {
as?: T;
}

export type PolymorphicRef<T extends ElementType> =
ComponentPropsWithRef<T>["ref"];

export type PolymorphicComponentProps<
T extends ElementType,
Props = {},
> = AsProps<T> &
ComponentPropsWithoutRef<T> &
Props & {
ref?: PolymorphicRef<T>;
};

0 comments on commit 09aa783

Please sign in to comment.