Typescript完全解读 —— 接口interface

接口interface

  • 基本用法
interface NameInfo {
  firstName:string,
  lastName:string
}
const getFullName=({firstName,lastName}:NameInfo):string=>{
   return `${firstName}${lastName}`
}
console.log(getFullName({firstName:'haha',lastName:'li'}))
  • 可选属性
interface Vegetable{
  color?:string, //?表示可选属性
  type:string
}
const getVegetable=({color,type}:Vegetable)=>{
  return `A ${color?(color+''):''}${type}`
}
console.log(getVegetable({type:'tomato'})) //A tomato
  • 多余属性检查
  • 绕开多余属性检查
interface Vegetable{
  color?:string, 
  type:string,
  [prop:string]:any //第一种用索引
}
const getVegetable=({color,type}:Vegetable)=>{
  return `A ${color?(color+''):''}${type}`
}
console.log(getVegetable({
  type:'tomato',
  color:'red',
  size:2
} as Vegetable)) //第二种用as类型断言

//第三种类型兼容性
const vegetableInfo={
  type:'tomato',
  color:'red',
  size:2
}
console.log(getVegetable(vegetableInfo)) //A red tomato
  • 只读属性
//限定属性为只读属性
interface Vegetable {
  color?:string,
  readonly type:string //readonly只读属性
}
const getVegetable=({color,type}:Vegetable)=>{
  return `A ${color?(color+''):''}${type}`
}
let vegetableObj:Vegetable={
  type:'tomato'
}
vegetableObj.type='carrot' //报错 提示typ是只读属性

//限定数组为只读
interface ArrInter {
  0:number,
  readonly 1:string
}
let arr:ArrInter=[1,'a']
arr[1]='b' //报错 提示typ是只读属性

  • 函数类型
type AddFunc=(num1:number,num2:number)=>number
const add:AddFunc=(n1,n2)=>n1+n2 //参数名字不必相同,但是位置要对应上
  • 索引类型
interface RoleDic {
  [id:number]:string
}
const role1:RoleDic={
  0:'super_admin'
}

interface RoleDic{
  [id:string]:string
}
const role2:RoleDic={
  a:'super_admin',
  1:'admin' //js默认把数字1转化为字符串1
  }
  • 继承接口
interface Vegetables{
  color:string
}
interface Tomato extends Vegetables{
  radius:number
}
interface Carrot extends Vegetables{
  length:number
}
const tomato:Tomato={
  radius:1,
  color:'red'
}
const carrot:Carrot={
  length:2,
  color:'blue'
}
  • 混合类型接口
interface Counter {
  ():void,
  count:number
}
const getCounter=():Counter=>{
  const c=()=>{c.count++}
  c.count=0
  return c
}
const counter:Counter=getCounter()
counter()
console.log(counter.count) //1
counter()
console.log(counter.count) //2
counter()
console.log(counter.count) //3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值