基础type最佳实践

  1. type AppProps = {
  2. /** string literals to specify exact string values, with a union type to join them together */
  3. status: "waiting" | "success";
  4. obj2: {}; // 对象最佳表示法
  5. /** 明确字段的对象 */
  6. obj3: {
  7. id: string;
  8. title: string;
  9. };
  10. /** array of objects! (common) */
  11. objArr: {
  12. id: string;
  13. title: string;
  14. }[];
  15. dict2: Record<string, MyTypeHere>; // equivalent to dict1
  16. /** function的最佳表示 */
  17. onClick: () => void;
  18. /** 有参数的function */
  19. onChange: (id: number) => void;
  20. /** 事件作为参数的最佳表示 */
  21. onClick(event: React.MouseEvent<HTMLButtonElement>): void;
  22. // react 节点的最佳表示
  23. children: React.ReactNode; // best, accepts everything (see edge case below)
  24. functionChildren: (name: string) => React.ReactNode; // recommended function as a child render prop type
  25. style?: React.CSSProperties; // to pass through style props
  26. onChange?: React.FormEventHandler<HTMLInputElement>; // form events! the generic parameter is the type of event.target
  27. };

Types or Interfaces?

需要外部感知&merge采用 interface, 仅自己用的采用 type

Here’s a helpful rule of thumb:

  • always use interface for public API’s definition when authoring a library or 3rd party ambient type definitions, as this allows a consumer to extend them via declaration merging if some definitions are missing.
  • consider using type for your React Component Props and State, for consistency and because it is more constrained. | Aspect | Type | Interface | | —- | —- | —- | | Can describe functions | ✅ | ✅ | | Can describe constructors | ✅ | ✅ | | Can describe tuples | ✅ | ✅ | | Interfaces can extend it | ⚠️ | ✅ | | Classes can extend it | 🚫 | ✅ | | Classes can implement it (implements) | ⚠️ | ✅ | | Can intersect another one of its kind | ✅ | ⚠️ | | Can create a union with another one of its kind | ✅ | 🚫 | | Can be used to create mapped types | ✅ | 🚫 | | Can be mapped over with mapped types | ✅ | ✅ | | Expands in error messages and logs | ✅ | 🚫 | | Can be augmented | 🚫 | ✅ | | Can be recursive | ⚠️ | ✅ |