Skip to content

Instantly share code, notes, and snippets.

@MR-Mostafa
Last active November 22, 2023 20:34
Show Gist options
  • Save MR-Mostafa/24655ea37ebbe6c2003d88b8193a5f0d to your computer and use it in GitHub Desktop.
Save MR-Mostafa/24655ea37ebbe6c2003d88b8193a5f0d to your computer and use it in GitHub Desktop.
Build strongly typed polymorphic components with React and TypeScript - Part 6
import * as React from 'react';
type Rainbow = "red" | "orange" | "yellow" | "green" | "blue" | "indigo" | "violet";
/**
* از تایپ پایین، این دو مورد حذف شدند:
* children: React.ReactNode
* React.ComponentPropsWithoutRef<C>
*/
type ButtonProps<C extends React.ElementType> = {
as?: C;
color?: Rainbow | "black";
};
/**
* یک تایپ جدید ایجاد کردیم
* در ری‌اکت می شه children یک جنریک تایپ هست که شامل پراپرتی React.PropsWithChildren تایپ
* و پراپرتی‌های کامپوننت رو هم به عنوان ورودی به این جنریک تایپ پاس دادیم
* ButtonProps<C> یعنی
*
* اضافه کردیم React.ComponentPropsWithoutRef<C> و سپس تایپ
*
* در نهایت هم از این تایپ، برای تعیین نوع پراپرتی‌های کامپوننت استفاده می‌کنیم
*/
type Props <C extends React.ElementType> = React.PropsWithChildren<ButtonProps<C>> & React.ComponentPropsWithoutRef<C>;
export const Button = <C extends React.ElementType = 'button'>({
as,
children,
...otherProps
}: Props<C>) => {
const Component = as || 'button';
return <Component {...otherProps}>{children}</Component>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment