手牵手系列之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=0
    return c
}
const counter :Counter=getCount()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值