TS 深入对象和函数

123 阅读1分钟

1.TS中深入对象语法

type Person={
name?:string
}
interface Person{
readonly name:string
}

在ts中问号表示类型可选,readonly表示是只读属性

ts中的索引签名和映射类型

//索引签名
type Hash={
[k:string]:unknow
}
//映射类型
type Hash={
[k in string]:unknow
}

ts中的索引签名和映射类型的区别:索引签名可以增加其他的属性,但是映射类型是MAP,不能添加其他的属性

2.在TS中对象语法完全适用于函数

type GetSum=(a:number,b:number)=>number

const sum:GetSum=(a,b)=>{return a+b}
//或者
const f1=(a:string):void=>{console.log(a)}
type F2=typeof f1
const f3:F2=(a)=>{
   a.split('.')
}

函数中的可选参数和默认参数

const Fun=(a:number,b?:string,c=true):void=>{
    //写方法体就行
}

3.TS函数中的类型谓词is

const isRect=(A:Shape):A is React=>{

     return "height" in A && "width" in A

    }

    

     const getShape=(cate:Shape)=>{

    //类型收窄

    if(isRect(cate)){

        console.log('it is  Rect ')

        }else{

        console.log('it is Circle')

        }

    }