Usage with TypeScript

Usage with TypeScript (TypeScript와 함께 사용하기)

모든 @mantine/* 패키지는 TypeScript와 완전히 호환돼요. 문서의 모든 예시는 TypeScript로 작성되어 있어서 수정 없이 프로젝트에 복사/붙여넣기할 수 있어요. 이 가이드는 @mantine/core 패키지가 내보내는 타입들에 익숙해지도록 도와줘요.

출처: 문서

본문

컴포넌트 props 타입

컴포넌트를 내보내는 각 @mantine/ 패키지는 그 컴포넌트의 props 타입도 내보내요. 컴포넌트 이름에 Props를 붙여 컴포넌트 props 타입을 import할 수 있어요. 예를 들어 Button과 DatePicker 컴포넌트 props를 이렇게 import해요:

import type { ButtonProps } from '@mantine/core';
import type { DatePickerProps } from '@mantine/dates';

props 타입에는 다형성 컴포넌트용과 일반 컴포넌트용 두 가지 변형이 있다는 점에 주의하세요. 일반 컴포넌트 props 타입에는 React.ComponentProps가 포함돼요. 여기서 X는 루트 요소 타입, 예를 들어 'div'예요.

일반 컴포넌트 props를 확장하는 예시:

import { Group, GroupProps } from '@mantine/core';

// Interface includes `React.ComponentProps<'div'>`
interface MyGroupProps extends GroupProps {
  spacing: number;
}

function MyGroup({ spacing, ...others }: MyGroupProps) {
  return <Group my={spacing} {...others} />;
}

다형성 컴포넌트 props 타입

다형성 컴포넌트 props 타입은 루트 요소가 component prop 값에 의존하므로 React.ComponentProps를 포함하지 않아요.

다형성 컴포넌트 props를 확장하는 예시:

import { Button, ButtonProps, ElementProps } from '@mantine/core';

interface MyButtonProps
  extends ButtonProps,
    ElementProps<'button', keyof ButtonProps> {
  height: number;
}

function MyButton({ height, ...others }: MyButtonProps) {
  return <Button style={{ height }} {...others} />;
}

Namespace 타입

모든 Mantine 컴포넌트는 관련 타입이 있는 namespace를 내보내요. 예를 들어 Button 컴포넌트 props는 Button.Props로 접근할 수 있어요:

import {  Button } from '@mantine/core';

// Same as `import type { ButtonProps } from '@mantine/core';`
type MyButtonProps = Button.Props;

ElementProps 타입

ElementProps는 React.ComponentProps와 비슷하지만 추가 기능이 있는 유틸리티 타입이에요. 네이티브 요소의 style prop을 Mantine의 style prop으로 교체하고, 두 번째 타입으로 전달한 속성을 생략할 수 있게 해줘요:

import { ButtonProps, ElementProps } from '@mantine/core';

// Equivalent of `React.ComponentProps<'button'>`
type ButtonElementProps = ElementProps<'button'>;

// Equivalent of `Omit<React.ComponentProps<'button'>, 'color' | 'onClick'>`
type OmitColor = ElementProps<'button', 'color' | 'onClick'>;

// Removes all Mantine component props from React component props
// to avoid props types conflicts
// Equivalent of `Omit<React.ComponentProps<'button'>, keyof ButtonProps>`
type OmitButtonProps = ElementProps<'button', keyof ButtonProps>;

MantineTheme 타입

MantineTheme는 theme 객체의 타입이에요. theme 객체를 인자로 받는 함수에 타입을 추가할 때 사용할 수 있어요:

import { MantineTheme, useMantineTheme } from '@mantine/core';

function getPrimaryColor(theme: MantineTheme) {
  return theme.colors.blue[5];
}

function Demo() {
  const theme = useMantineTheme();
  return <div style={{ color: getPrimaryColor(theme) }} />;
}

MantineThemeOverride 타입

MantineThemeOverride 타입은 MantineTheme의 깊은 부분(deep partial)이에요. theme override를 인자로 받는 함수에 사용할 수 있어요:

import {
  createTheme,
  MantineThemeOverride,
  mergeThemeOverrides,
} from '@mantine/core';

const baseTheme = createTheme({
  fontFamily: 'Helvetica, sans-serif',
});

function mergeThemes(themes: MantineThemeOverride[]) {
  return mergeThemeOverrides(baseTheme, ...themes);
}

const overrideTheme = createTheme({
  primaryColor: 'blue',
});

const overrideTheme2 = createTheme({
  cursorType: 'pointer',
});

const mergedTheme = mergeThemes([overrideTheme, overrideTheme2]);

MantineColorScheme 타입

MantineColorScheme은 'light' | 'dark' | 'auto' 값들의 유니언이에요. color scheme을 인자로 받는 함수에 타입을 추가할 때 사용할 수 있어요:

import {
  MantineColorScheme,
  useMantineColorScheme,
} from '@mantine/core';

function getComputedColorScheme(colorScheme: MantineColorScheme) {
  return colorScheme === 'auto' ? 'light' : colorScheme;
}

function Demo() {
  const { colorScheme } = useMantineColorScheme();
  const computed = getComputedColorScheme(colorScheme);
}

MantineSize 타입

MantineSize 타입은 'xs' | 'sm' | 'md' | 'lg' | 'xl' 값들의 유니언이에요. size를 인자로 받는 다양한 props — 예를 들어 radius, shadow, p — 에 타입을 추가할 때 사용할 수 있어요:

import { MantineSize, Paper } from '@mantine/core';

interface DemoProps {
  size: MantineSize;
  radius: MantineSize | (string & {}) | number;
  shadow: MantineSize | string;
}

function Demo({ size, radius, shadow }: DemoProps) {
  return <Paper radius={radius} shadow={shadow} p={size} m={size} />;
}

Theme 객체 선언

.d.ts 파일에서 MantineTheme 인터페이스를 확장해 theme.other와 theme.colors 타입을 바꿀 수 있어요. 프로젝트 어디든(tsconfig.json에 포함되어야 함) mantine.d.ts를 만들어 theme 객체 타입을 확장하세요.

theme.other를 오버라이드하려면:

// mantine.d.ts
declare module '@mantine/core' {
  export interface MantineThemeOther {
    myCustomProperty: string;
    myCustomFunction: () => void;
  }
}

theme.colors를 오버라이드하려면:

import {
  DefaultMantineColor,
  MantineColorsTuple,
} from '@mantine/core';

type ExtendedCustomColors =
  | 'primaryColorName'
  | 'secondaryColorName'
  | DefaultMantineColor;

declare module '@mantine/core' {
  export interface MantineThemeColorsOverride {
    colors: Record<ExtendedCustomColors, MantineColorsTuple>;
  }
}

theme.spacing, theme.radius, theme.breakpoints, theme.fontSizes, theme.lineHeights, theme.shadows 같은 size 관련 타입도 비슷하게 커스터마이즈할 수 있어요.

theme.spacing과 theme.radius를 오버라이드하려면:

import {
  DefaultMantineSize,
  MantineThemeSizesOverride,
} from '@mantine/core';

type ExtendedCustomSpacing =
  | 'xxl'
  | 'xxxs'
  | DefaultMantineSize;

type ExtendedCustomRadius =
  | 'xxs'
  | DefaultMantineSize;

declare module '@mantine/core' {
  export interface MantineThemeSizesOverride {
    spacing: Record<ExtendedCustomSpacing, string>;
    radius: Record<ExtendedCustomRadius, string>;
  }
}

theme 타입을 확장하는 것은 필수가 아니라는 점에 주의하세요. theme 객체 타입을 더 엄격하게 만들고 에디터에서 자동완성을 추가하고 싶을 때만 필요해요.

커스텀 variant 타입

mantine.d.ts 파일에서 {x}Props 인터페이스를 새 variant 타입으로 확장해 커스텀 variants 타입을 정의할 수 있어요.

Button 컴포넌트에 커스텀 variant 타입을 추가하는 예시:

import { ButtonVariant, MantineSize } from '@mantine/core';

type ExtendedButtonVariant = ButtonVariant | 'contrast' | 'radial-gradient';

declare module '@mantine/core' {
  export interface ButtonProps {
    variant?: ExtendedButtonVariant;
  }
}

더 알아보기 (Learn more)