typescript_对象类型接口

  1. 对象类型接口
interface List {
   readonly id : number, //只读属性不可修改
    name : string,
    // [x : string] : any
    age ? : string
};

interface Result {
    data:List[]
};
function render(result : Result){
    result.data.forEach((item)=>{
        console.log(item.id,item.name);
        if(item.age){
            console.log(item.age)
        }
        // item.id++;只读属性不可更改
    })
}

let result = {
    data:[
        {
            id : 1 , name : 'A'
        },
        {
            id : 2 , name : "B"
        }
    ]
}
// render(result);
//对象类型, 是鸭子类型,只要符合基本的条件即可, 所以可以额外增加字段也不会报错
//如果直接将值传入函数中,而不是通过变量的方式传入, 那么会报错
//这里可以用 as断言,或者字符串索引签名,[x : string] : any; 用任意字符串索引值
// render({
//     data:[
//         {
//             id : 1 , name : 'A' , age : "c"
//         },
//         {
//             id : 2 , name : "B"
//         }
//     ]
// });

//数值索引签名
//相当于是一个字符串类型的数组
//用任意的数值去索引,得到的是string类型
interface  StringArray {
    [index : number] : string
}

//字符串索引
//注意: 如果数字索引和字符串索引混合使用的话,数字索引是字符串索引的子类型,也就是说,数值类型返回的类型必须和字符串索引返回的类型相等,或者字符串索引的返回值是any
interface Names {
    [x : string] : string,
    [index : number] : string
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值