这一篇是不涉及泛型的高级类型
1、联合类型
如果一个变量可以是多个类型,那么就可以使用联合类型来表示。
let a: number | string
a = 1
a = '1'
但是这么写的话,当TS不知道你准确的类型时只能使用这些类型共有的属性方法。
2、交叉类型
交叉类型用于将多个类型合并为一个新类型,使用&符号
type a = { name: string }
type b = { age: number }
type c = a & b
let c: c = { name: 'a', age: 1 }
3、类型别名
上面的例子中的type就是类型别名关键字,使用类型别名让我们代码可读性更高。
type和interface都可以描述一个对象
// 对象
type a = { name: string }
interface b { name: string }
const a: a = {name:'1'}
const b: b = {name:'1'}
// 函数
type c = (str: string) => string
interface d {
(str: string): string
}
const c: c = (str: string) => str
const d: d = (str: string) => str
那么type和interface有什么同异呢
相同点:都可以形容对象和函数,都可以继承,type使用交叉类型,interface使用extends
不同点:
-
interface(接口) 是 TS 设计出来用于定义对象类型的,可以对对象的形状进行描述。
-
type 是类型别名,用于给各种类型定义别名,让 TS 写起来更简洁、清晰。
-
type 可以声明基本类型、联合类型、交叉类型、元组,interface 不行
-
interface可以合并重复声明,type 不行
4、typeof类型保护
使用 typeof 操作符可以在运行时检查变量的类型。
上面的联合类型怎么在没有确定值之前调用有一个类型特有的方法呢 使用typeof
type param = number | string
const a = (param: param) => {
param.length // 报错 类型“number”上不存在属性“length”
}
type param = number | string
const a = (param: param) => {
if (typeof param === 'string') {
param.length // 这样就不报错了
}
}
5、类型断言
上面的例子也可以使用类型断言 as来告诉ts我就是某个类型,但是只能时联合类型中包含的类型,不能是其他的类型。
type param = number | string
const a = (param: param) => {
let strParam = param as string
strParam.length
}
6、字面量类型
字面量就是一些常量
type Sex = '男' | '女'