手牵手系列之TypeScript接口

编程入门 行业动态 更新时间:2024-10-22 19:22:56

<a href=https://www.elefans.com/category/jswz/34/1755206.html style=手牵手系列之TypeScript接口"/>

手牵手系列之TypeScript接口

基本用法

// 普通形式
const getFullName = ({ firstName, lastName }: { firstName: string, lastName: string }) => {return `${firstName} ${lastName}`
}
console.log(getFullName({firstName: 'hhh',lastName: 'Li'})
)// 接口定义
interface NameInfo{firstName:string,lastName:string
}const getFullName = ({ firstName, lastName }: NameInfo) => {return `${firstName} ${lastName}`
}
console.log(getFullName({firstName: 'hhh',lastName: 'Li'})
)

可选属性

// color?:string ? 表示可选属性
interface Vegetable{color?:string,type:string,
}const getVegetable = ({color,type}:Vegetable):string=>{return `A ${color ? (color + ' ') : ''}${type} `
}getVegetable({type:'tomato',
})

绕开多余属性检查

const getVegetable = ({color,type}:Vegetable):string=>{return `A ${color ? (color + ' ') : ''}${type} `
}// 索引签名 [prop:string]:any
interface Vegetable{color?:string,readonly type:string,[prop:string]:any
}getVegetable({color:'red',type:'tomato',size:2
})// 或者使用类型断言 as Vegetable
getVegetable({color:'red',type:'tomato',size:2
} as Vegetable)// 或者使用类型兼容性
const vagetableInfo = {color:'red',type:'tomato',size:2
}
getVegetable(vagetableInfo)

只读属性

// readonly 只读属性
interface Vegetable{color?:string,readonly type:string,
}let vagetableObj : Vegetable={color:'red',type:'tomato',
}vagetableObj.type='carrot' // 报错

函数类型

type AddFnc = (num1:number,num2:number) =>number
const add: AddFnc=(n1,n2)=>n1+n2

索引类型

// 索引类型
interface RoleDic{[id:number]:string
}
const role1:RoleDic={0:'super_admin'
}// 如果属性名是字符串类型,即使设置属性名为数字,也是可以的,因为会被转成string类型
interface RoleDic{[id:string]:string
}
const role2:RoleDic={a:'admin'0:'super_admin'
}

继承接口

// 接口继承
interface Vegetables{color:string
}
interface Tomato extends Vegetables{radius:number
}
interface Carrot{length:number
}
const tomato:Tomato={radius:1,color:'red'
}
const carrot:Carrot={length:2
}

混合类型接口

// 混合类型接口
interface Counter{():void,count:number
}
const getCount =():Counter=>{const c =()=>{c.count++}c.count=0return c
}
const counter :Counter=getCount()

更多推荐

手牵手系列之TypeScript接口

本文发布于:2024-02-07 08:35:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755074.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:手牵手   接口   系列之   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!