TypeScript 支持 #

概述 #

Ant Design 提供了完整的 TypeScript 类型定义,帮助开发者在 TypeScript 项目中获得更好的开发体验。

基础配置 #

tsconfig.json #

json
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

组件类型 #

函数组件 #

tsx
import React from 'react';

interface UserCardProps {
  name: string;
  email: string;
  avatar?: string;
  onClick?: () => void;
}

const UserCard: React.FC<UserCardProps> = ({
  name,
  email,
  avatar,
  onClick
}) => {
  return (
    <div onClick={onClick}>
      <img src={avatar} alt={name} />
      <h3>{name}</h3>
      <p>{email}</p>
    </div>
  );
};

export default UserCard;

泛型组件 #

tsx
import React from 'react';

interface ListProps<T> {
  items: T[];
  renderItem: (item: T, index: number) => React.ReactNode;
}

function List<T>({ items, renderItem }: ListProps<T>) {
  return (
    <div>
      {items.map((item, index) => renderItem(item, index))}
    </div>
  );
}

export default List;

Ant Design 组件类型 #

Button 类型 #

tsx
import { Button, ButtonProps } from 'antd';

const MyButton: React.FC<ButtonProps> = (props) => {
  return <Button {...props} />;
};

const App = () => {
  return (
    <MyButton type="primary" onClick={() => console.log('clicked')}>
      按钮
    </MyButton>
  );
};

Form 类型 #

tsx
import { Form, Input, Button } from 'antd';

interface UserFormValues {
  name: string;
  email: string;
  phone?: string;
}

const UserForm: React.FC = () => {
  const [form] = Form.useForm<UserFormValues>();

  const onFinish = (values: UserFormValues) => {
    console.log(values);
  };

  return (
    <Form form={form} onFinish={onFinish}>
      <Form.Item<UserFormValues>
        name="name"
        label="姓名"
        rules={[{ required: true }]}
      >
        <Input />
      </Form.Item>
      <Form.Item<UserFormValues>
        name="email"
        label="邮箱"
        rules={[{ required: true, type: 'email' }]}
      >
        <Input />
      </Form.Item>
      <Button type="primary" htmlType="submit">
        提交
      </Button>
    </Form>
  );
};

Table 类型 #

tsx
import { Table } from 'antd';

interface User {
  id: string;
  name: string;
  email: string;
  age: number;
}

const columns: ColumnsType<User> = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '年龄',
    dataIndex: 'age',
    key: 'age',
    sorter: (a, b) => a.age - b.age,
  },
];

const UserTable: React.FC<{ data: User[] }> = ({ data }) => {
  return <Table<User> columns={columns} dataSource={data} rowKey="id" />;
};

自定义 Hooks 类型 #

tsx
import { useState, useEffect } from 'react';

interface UseRequestResult<T> {
  data: T | null;
  loading: boolean;
  error: Error | null;
}

function useRequest<T>(url: string): UseRequestResult<T> {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    setLoading(true);
    fetch(url)
      .then((res) => res.json())
      .then((data) => setData(data))
      .catch((err) => setError(err))
      .finally(() => setLoading(false));
  }, [url]);

  return { data, loading, error };
}

export default useRequest;

API 类型定义 #

tsx
interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
}

interface User {
  id: string;
  name: string;
  email: string;
}

interface UserListParams {
  page: number;
  pageSize: number;
  name?: string;
}

export const userApi = {
  getList: (params: UserListParams): Promise<ApiResponse<User[]>> => {
    return request.get('/users', { params });
  },
  getDetail: (id: string): Promise<ApiResponse<User>> => {
    return request.get(`/users/${id}`);
  },
  create: (data: Omit<User, 'id'>): Promise<ApiResponse<User>> => {
    return request.post('/users', data);
  },
};

类型工具 #

通用类型 #

tsx
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

type Required<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;

type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

type Partial<T> = {
  [P in keyof T]?: T[P];
};

组件 Props 类型 #

tsx
type WithChildren<T = {}> = T & { children?: React.ReactNode };

type WithStyle<T = {}> = T & { style?: React.CSSProperties };

type WithClassName<T = {}> = T & { className?: string };

最佳实践 #

1. 使用类型导入 #

tsx
import type { ButtonProps, TableProps } from 'antd';
import { Button, Table } from 'antd';

2. 定义类型文件 #

text
src/
├── types/
│   ├── index.d.ts        全局类型
│   ├── api.d.ts          API 类型
│   └── components.d.ts   组件类型

3. 使用泛型 #

tsx
interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}

const fetchData = async <T>(url: string): Promise<T> => {
  const response = await fetch(url);
  return response.json();
};

4. 类型守卫 #

tsx
function isUser(data: unknown): data is User {
  return (
    typeof data === 'object' &&
    data !== null &&
    'id' in data &&
    'name' in data
  );
}

if (isUser(response)) {
  console.log(response.name);
}

常见问题 #

1. 组件 Props 类型 #

tsx
import { ButtonProps } from 'antd';

const MyButton: React.FC<ButtonProps> = (props) => {
  return <Button {...props} />;
};

2. 表单字段类型 #

tsx
import { Form } from 'antd';

interface FormValues {
  name: string;
  age: number;
}

const [form] = Form.useForm<FormValues>();

3. 表格列类型 #

tsx
import { Table, ColumnsType } from 'antd';

const columns: ColumnsType<User> = [
  { title: '姓名', dataIndex: 'name' },
];

恭喜你完成了 Ant Design 文档的学习!

最后更新:2026-03-28