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
20 lines
680 B
// 映射类型:基于旧类型创建新类型
|
|
|
|
type PropKeys = 'x' | 'y' | 'z' // 联合类型
|
|
type Type1 = { x: number; y: number; z: number }
|
|
|
|
// 使用映射类型进行简化
|
|
type Type2 = { [Key in PropKeys]: number } // key 表示 PropKeys 联合类型中的任意一个
|
|
|
|
// 映射类型只能在类型别名中使用,不能在接口中使用
|
|
// 错误演示:
|
|
/*
|
|
* interface Type3 {
|
|
* [Key in PropKeys]: number
|
|
* }
|
|
*/
|
|
|
|
|
|
// 根据对象类型创建新类型
|
|
type Props = { a: number; b: string; c: boolean }
|
|
type Type3 = { [key in keyof Props]: number } // key in 表示 key 可以是 Props 中所有个键名称中的任意一个,类型为 number
|