How to Use TypeScript Generics with Ant Design Select and Table Components

Ant Design's Select and Table components accept TypeScript generic parameters that enforce type safety across values, options, and row data, eliminating any types and enabling full IntelliSense for callbacks and render functions.

The ant-design/ant-design repository implements its core UI components with sophisticated generic TypeScript patterns. By leveraging these built-in generic parameters, you can bind component props directly to your domain models, ensuring that onChange handlers, column renderers, and selection callbacks all receive correctly typed arguments.

Understanding TypeScript Generics in Ant Design Components

Select Component Generic Parameters

The Select component in components/select/index.tsx exposes two primary generic parameters: ValueType and OptionType. According to the source code (lines 38-51), SelectProps is defined as:

SelectProps<ValueType = any, OptionType extends BaseOptionType = DefaultOptionType>
  • ValueType controls the type of the selected value passed to onChange and received from value props.
  • OptionType extends BaseOptionType and defines the shape of objects in the options array.

Table Component Generic Parameters

The Table component uses a single RecordType generic to type the entire data pipeline. In components/table/Table.tsx, the component is declared as:

const Table = <RecordType extends AnyObject = AnyObject>(props: TableProps<RecordType>, ref: React.Ref<Reference>) => ...

This generic propagates through TableProps<RecordType> defined in components/table/InternalTable.tsx, ensuring that dataSource is typed as RecordType[] and all column render functions receive strongly typed record arguments.

Why Explicit Generics Matter for Type Safety

When you omit generic arguments, Ant Design components fall back to any or broad default types. This eliminates compile-time safety for value, options, and dataSource, and disables auto-completion for column render callbacks.

Specifying explicit generics provides:

  • Strict type inference – onChange handlers receive the exact ValueType you declared, not any.
  • Strongly-typed column render functions – The record parameter in render callbacks is fully typed, enabling property-level autocomplete.
  • Self-documenting PropTypes – IDEs display concrete types instead of any, making the component API discoverable.

Implementation Details from the Source Code

Select Generic Forwarding in components/select/index.tsx

The Select component is a wrapper around RcSelect from @rc-component/select. The wrapper's type definition spreads RcSelectProps<ValueType, OptionType> (lines 48-51), then forwards mergedProps to the underlying component. Because the wrapper maintains generic parameters throughout the declaration, type safety persists through the entire render tree without leakage to any.

Table Generic Declaration in components/table/Table.tsx

The exported ForwardTable preserves generics through React's forward-ref pattern. The declaration const Table = <RecordType extends AnyObject = AnyObject>... ensures that any consumer importing Table can pass a concrete record type. This generic flows into components/table/InternalTable.tsx where TableProps<RecordType> defines dataSource?: RecordType[], column definitions, and selection callbacks.

Practical Code Examples

Typed Select with Custom Option Objects

When working with complex option shapes, declare an interface and pass it as the second generic parameter:

// types.ts
export interface CountryOption {
  label: string;
  value: string;
  flag: string;
}

// Component.tsx
import { Select } from 'antd';
import type { CountryOption } from './types';

const countries: CountryOption[] = [
  { label: 'China', value: 'CN', flag: '/flags/cn.svg' },
  { label: 'United States', value: 'US', flag: '/flags/us.svg' },
];

export default function CountrySelect() {
  const handleChange = (value: string) => {
    console.log('selected country code:', value);
  };

  return (
    <Select<string, CountryOption>
      style={{ width: 200 }}
      placeholder="Select country"
      options={countries}
      optionRender={(option) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <img src={option.flag} alt="" style={{ width: 20, marginRight: 8 }} />
          {option.label}
        </div>
      )}
      onChange={handleChange}
    />
  );
}

The generic signature <string, CountryOption> binds ValueType to string and OptionType to your custom interface, ensuring optionRender receives fully typed objects.

Typed Table with Column Definitions

For the Table component, type your columns using ColumnsType<RecordType>:

// types.ts
export interface User {
  id: number;
  name: string;
  email: string;
  createdAt: Date;
}

// Component.tsx
import { Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { User } from './types';

const data: User[] = [
  { id: 1, name: 'Ada', email: 'ada@example.com', createdAt: new Date() },
  { id: 2, name: 'Bob', email: 'bob@example.com', createdAt: new Date() },
];

const columns: ColumnsType<User> = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
    render: (text, record) => (
      // record is fully typed as User
      <a href={`mailto:${record.email}`}>{text}</a>
    ),
  },
  {
    title: 'Created',
    dataIndex: 'createdAt',
    key: 'createdAt',
    render: (date: Date) => date.toLocaleDateString(),
  },
];

export default function UserTable() {
  return (
    <Table<User>
      rowKey="id"
      columns={columns}
      dataSource={data}
      pagination={false}
    />
  );
}

By declaring columns: ColumnsType<User> and Table<User>, the record parameter in render functions is inferred as User, preventing property access errors.

Union Types in Select Tags Mode

When using mode="tags", you can define union types for heterogeneous value collections:

type TagValue = string | number;

const options = [
  { label: 'One', value: 1 },
  { label: 'Two', value: 2 },
  { label: 'Apple', value: 'apple' },
];

<Select<TagValue, typeof options[number]>
  mode="tags"
  style={{ width: 300 }}
  options={options}
  onChange={(vals) => console.log('selected:', vals)}
/>

Here typeof options[number] extracts the union type of array elements, synchronizing the option type with your data definition automatically.

Summary

  • Ant Design's Select and Table components expose generic parameters (ValueType/OptionType and RecordType) defined in components/select/index.tsx and components/table/Table.tsx.
  • Explicit generics prevent fallback to any, enabling strict type checking for onChange handlers, column render functions, and data sources.
  • Use Select<ValueType, OptionType> for custom option shapes and Table<RecordType> with ColumnsType<RecordType> for fully typed data tables.
  • The generic types propagate through React's forward-ref pattern and underlying RC components, preserving type safety throughout the component tree.

Frequently Asked Questions

What happens if I don't provide generic arguments to Ant Design Select or Table?

If you omit the generic parameters, the components default to any or broad base types. This disables compile-time checking for value, options, and dataSource props, and removes IntelliSense from render callbacks and event handlers, increasing the risk of runtime type errors.

Can I use interface definitions from my domain models as the generic arguments?

Yes. Both Select and Table are designed to accept any concrete type that satisfies the underlying constraints. For Select, your option type must extend BaseOptionType. For Table, your record type must extend AnyObject (essentially any object). Pass your domain interfaces directly: Select<string, MyDomainOption> or Table<MyDomainRecord>.

How do the generics affect the Table column render function types?

When you declare columns: ColumnsType<RecordType> or use Table<RecordType>, the render function signature changes from (text: any, record: any, index: number) => ReactNode to (text: DataIndexValue, record: RecordType, index: number) => ReactNode. This provides full autocomplete and type checking for record properties inside your render functions.

Do Ant Design's generic types work with React's forwardRef pattern?

Yes. The Table component in components/table/Table.tsx specifically uses React.forwardRef while preserving the RecordType generic. The declaration const Table = <RecordType extends AnyObject = AnyObject>(props: TableProps<RecordType>, ref: React.Ref<Reference>) => ... ensures that the generic parameter flows through the forward-ref wrapper to the underlying component implementation.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →