You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

20 lines
680 B

2 years ago
  1. // 映射类型:基于旧类型创建新类型
  2. type PropKeys = 'x' | 'y' | 'z' // 联合类型
  3. type Type1 = { x: number; y: number; z: number }
  4. // 使用映射类型进行简化
  5. type Type2 = { [Key in PropKeys]: number } // key 表示 PropKeys 联合类型中的任意一个
  6. // 映射类型只能在类型别名中使用,不能在接口中使用
  7. // 错误演示:
  8. /*
  9. * interface Type3 {
  10. * [Key in PropKeys]: number
  11. * }
  12. */
  13. // 根据对象类型创建新类型
  14. type Props = { a: number; b: string; c: boolean }
  15. type Type3 = { [key in keyof Props]: number } // key in 表示 key 可以是 Props 中所有个键名称中的任意一个,类型为 number