Back to Ant Design

Util

components/_util/index.en-US.md

6.5.02.2 KB
Original Source

Available since 5.13.0.

GetRef

Get the ref property definition of the component, which is very useful for components that are not directly exposed or child components.

tsx
import { Select } from 'antd';
import type { GetRef } from 'antd';

type SelectRefType = GetRef<typeof Select>; // BaseSelectRef

GetProps

Get the props property definition of the component:

tsx
import { Checkbox } from 'antd';
import type { GetProps } from 'antd';

type CheckboxGroupType = GetProps<typeof Checkbox.Group>;

Also supports getting the property definition of Context:

tsx
import type { GetProps } from 'antd';

interface InternalContextProps {
  name: string;
}

const Context = React.createContext<InternalContextProps>({ name: 'Ant Design' });

type ContextType = GetProps<typeof Context>; // InternalContextProps

Difference from React.ComponentProps {#react-componentprops-diff}

React.ComponentProps is the official React utility type for getting props accepted by intrinsic elements or React components, such as React.ComponentProps<'button'> or React.ComponentProps<typeof Button>. GetProps is an Ant Design supplementary type: it does not support intrinsic element names, but besides React components, it can also directly extract the value type from React.Context, or pass through an existing props type object.

GetProp

Get the single props or context property definition of the component. It has encapsulated NonNullable, so you don't have to worry about it being empty:

tsx
import { Select } from 'antd';
import type { GetProp, SelectProps } from 'antd';

// Both of these can work
type SelectOptionType1 = GetProp<SelectProps, 'options'>[number];
type SelectOptionType2 = GetProp<typeof Select, 'options'>[number];
type ContextOptionType = GetProp<typeof Context, 'name'>;

Also supports getting the return type of a function property through the third parameter Return:

tsx
import type { GetProp } from 'antd';

interface Props {
  func?: (value: number) => string;
  configOrFunc?: { configA?: string } | (() => { anotherB?: string });
}

type OnChangeReturn = GetProp<Props, 'func', 'Return'>; // string
type ClassNamesReturn = GetProp<Props, 'configOrFunc', 'Return'>; // { anotherB?: string }