复写class接口方式, 这里用antd来举例子

  1. /types/global.ts
  2. import * as PropTypes from 'prop-types';
  3. import { Table } from 'antd';
  4. declare type TableSize = 'default' | 'middle' | 'small';
  5. export declare class TableT<T> extends Table<T> {
  6. static propTypes: {
  7. dataSource: PropTypes.Requireable<any[]>;
  8. columns: PropTypes.Requireable<any[]>;
  9. prefixCls: PropTypes.Requireable<string>;
  10. useFixedHeader: PropTypes.Requireable<boolean>;
  11. rowSelection: PropTypes.Requireable<object>;
  12. className: PropTypes.Requireable<string>;
  13. size: PropTypes.Requireable<TableSize>;
  14. loading: PropTypes.Requireable<boolean | object>;
  15. bordered: PropTypes.Requireable<boolean>;
  16. onChange: PropTypes.Requireable<(...args: any[]) => any>;
  17. locale: PropTypes.Requireable<object>;
  18. dropdownPrefixCls: PropTypes.Requireable<string>;
  19. sortDirections: PropTypes.Requireable<any[]>;
  20. batchButtons: any;
  21. };
  22. }
  23. /xxx/xxx.tsx
  24. import { TableT } from 'types/global.ts';
  25. /// <reference path = "types/global.ts" />
  26. class demo extends React.Component {
  27. render(){
  28. return(<Table ... />);
  29. }
  30. }

如果你的eslint或tslint报错了,告诉你某某某组件没有某个参数或者方法

  1. // 使用接口基础的方式,讲属性或方法添加上
  2. interface HTMLElementDom extends HTMLElement {
  3. select?: () => void;
  4. value?: string;
  5. }
  6. // 使用时
  7. (dom as HTMLElementDom).value
  8. (dom as HTMLElementDom).select();

自定义属性

  1. // 新版本的,建议使用此种语法
  2. declare module 'react' {
  3. interface HTMLAttributes<T> extends DOMAttributes<T> {
  4. block?: string
  5. element?: string
  6. modifiers?: Modifiers // <-- custom interface
  7. }
  8. }
  9. // 旧版本的
  10. declare namespace React {
  11. interface HTMLProps<T> extends HTMLAttributes, ClassAttributes<T> {
  12. }
  13. }
  14. // 一个例子
  15. import * as React from 'react';
  16. declare module 'react' {
  17. interface HTMLProps<T> {
  18. block?:string;
  19. element?:string;
  20. modifiers?:string;
  21. }
  22. }
  23. export const Foo = () => {
  24. return (
  25. <div block="123" element="456">
  26. </div>
  27. )
  28. };
  29. // 定义公共
  30. import * as React from 'react';
  31. import './react_augmented';

传递Event

  1. public selectFn: (event: React.MouseEvent<HTMLSpanElement, MouseEvent>) => void = (e) => {
  2. // 这里要强制类型转换才可以使用getAttribute方法
  3. const target = (e.target as HTMLElement);
  4. console.log('selectFn', target.getAttribute('uid'));
  5. }
  6. <Component selectFn={this.selectFn} />
  7. interface Props {
  8. selectFn(event: React.MouseEvent<HTMLSpanElement, MouseEvent>): void;
  9. }