1.匿名函数 自行推导
// 匿名函数的类型
let arr = ['a','b','c',9]
arr.forEach(item => {
// 这个item是可以推导出来的 他一定是string类型或者number类型 所以可以写 也可以不写
console.log(item)
})
2. // 对象类型 可选类型
// 参数本身是可选的 它的本质是一个联合类型 如下的z 就是 z:boolean|undefined
function fn (point:{x:string,y:number,z?:boolean}) :void{
// ?表示可选类型
console.log(point.x)
console.log(point.y)
console.log(point.z) // 如果没传的话,那么就会输出undefined
}
3. // 联合类型
function fn2(id:number|string){
// 当使用联合类型的时候 要小心 不一定对他的所有操作都是有效的
// 可以来判断一下
if(typeof id === 'string'){
id = id.concat('%')
}else {
id += 1
}
console.log(id)
return id
}
4. // 类型别名
type UniType = string|number|boolean //起一个别名
function fn3(arg:UniType){
return arg
}
fn3('s')
5.// 类型断言
let someValue : any ='天津影久'
let lengthString : number = (someValue as string).length
//就可以理解为 我很确定这个 someValue就是某一种类型
6. // 非空类型断言
function logMes(mes?:string){
console.log(mes.length)
// 在编译的时候不会通过
}
logMes()
// 要修改为如下
function logMes2(mes?:string){
console.log(mes!.length)
// 在编译的时候就可以通过了
// 意思就是 我再调用的时候,一定会传一个参数进去
// 所以它就会有length
}
7. 可选链的使用
type Person = {
name:string,
friend?:{
name:string,
age?:number
}
}
const info : Person = {
name:'孙策',
friend:{
name:'周瑜'
}
}
console.log(info.name)
console.log(info.friend!.age)
//只是逃过了编译阶段 但在使用的时候 不一定是正确的
console.log(info?.friend.name)
// 在这里加一个 ? , 意思就是 如果它有这个friend属性,
//那就接着往下走,如果直接没有friend,那就整个语句就返回undefined
// 这个就是可选链
8.字面量类型
type position = 'left' | 'center' | 'right'
let aligin : position = 'left'
//只能选择其中的一个 这才是字面量类型存在的意义
解决字面量推理类型的问题
1.使用类型断言
type Method = 'post'|'get'
function request(url:string,method:Method){
}
const urlObj = {
url:'http://127.0.0.1:3000',
method:'get'
}
request(urlObj.url,urlObj.method as Method)
// 本来urlObj.methods 得到的是一个字符串
//在这里用类型缩小 as 将能接收到的字符串
// 缩小为 Method 的类型 // post或者 get
2.使用 as const 来规范
type Method = 'post'|'get'
function request(url:string,method:Method){
}
const urlObj = {
url:'http://127.0.0.1:3000',
method:'get'
} as const
request(urlObj.url,urlObj.method)
3.使用 type来规范
type Method = 'post'|'get'
type Request = {
url:string,
method:Method
//相比于第一种 直接在类型的method 里 直接用 type Method 类型
}
function request(url:string,method:Method){
}
const urlObj :Request= {
url:'http://127.0.0.1:3000',
method:'get'
}
request(urlObj.url,urlObj.method)
9 类型缩小
type IDType = number | string
// if判断缩小类型 switch instanceof in等都可以进行类型缩小
function printID(id:IDType){
console.log(id)
//这里的id是 IDType类型 如果不判断 不能直接使用 string 或 number 的方法
if(typeof id === 'string'){
console.log(id.indexOf('d'))
}else {
id += 4
}
}
class A{t(){}}
class B{b(){}}
type s = A|B
function work(p:s){
if(p instanceof A){
p.t()
}else {
p.b()
}
}