type 的使用
type 的使用#
作用:给已有类型取别名 和 定义一个新的类型 (搭配联合类型使用)
1. 类型别名#
语法 : type 别名 = 类型
实例 :
type St = string // 定义
let str1:St = 'abc'
let str2:string = 'abc'
2. 自定义类型#
语法 : type 别名 = 类型 | 类型1 | 类型2
实例 :
type NewType = string | number // 定义类型
let a: NewType = 1
let b: NewType = '1'
3. 泛型定义#
语法: type 别名<T> = 类型<T> | 类型1<T> | 类型2<T>
实例 :
type NewType<T> = {
name: T
}
let a : NewType<number> = { name: 0 }
let b : NewType<string> = { name: '0' }
4. 联合类型 (相当于继承类型)#
语法:type 别名 = 类型 & 类型1 & 类型2
示例:
type User = {
name: string;
age?: number;
}
type Job = {
jobs: string;
}
type UserInfo = User & Job;
本文由 note.batype.com 导入。
相关文章
- 对象属性只读(递归)DeepReadonly
实现一个泛型 DeepReadonly<T ,它将对象的每个参数及其子对象递归地设为只读。
- 获取只读属性 GetReadonlyKeys
实现泛型 GetReadonlyKeys<T , GetReadonlyKeys<T 返回由对象 T 所有只读属性的键组成的联合类型。
- 实现 Omit
不使用 Omit 实现 TypeScript 的 Omit<T, K 泛型。