TypeScrip-03(接口和对象类型)

目录

interface 重名 、重合

任意属性 [propName: string]

可选 ? 操作符、 readonly 只读

interface 接口继承

interface 定义函数类型


在 ts 中,定义对象的方式要用关键字 interface(接口),我的理解是使用interface来定义一种约束,让数据的结构满足约束的格式。

定义方式如下:

//必须与接口保持一致, 使用接口约束的时候不能多一个属性也不能少一个属性
interface Person {
    b:string,
    a:string
}
// 这样写是会报错的 因为我们在person定义了a,b但是对象里面缺少b属性 
const person:Person  = {
    a:"ls"
}

interface 重名 、重合

// 不能多属性、不能少属性 
interface Axxsxs {
    name: string,
    age: number
}
// 重名重合 
interface Axxsxs {
    sex: number
}
// 正确定义方式 
let a: Axxsxs = {
    name: 'lx',
    age: 18,
    sex: 2
}

任意属性 [propName: string]

interface 任意 key

需要注意的是,一旦定义了任意属性,那么确定属性和可选属性的类型都必须是它的类型的子集

// 只有 name、age 需要校验
interface Axxsxs {
    name: string,
    age: number,
    // 索引签名
    [propName: string]: any
}

/*
    1、例子中看到接口中并没有定义a,b但是并没有报错
    2、因为我们定义了[propName: string]: any;
    3、允许添加新的任意属性
*/

let a: Axxsxs = {
    name: 'lx',
    age: 18,
    a: 1,
    b: 2
}

可选 ? 操作符、 readonly 只读

interface Axxsxs {
    name: string,
    age?: number, // 可选 
    readonly cd: () =>boolean // 设置只读
}


let a: Axxsxs = {
    name: 'lx',
    age: 18,  // 可以写可以不写 
    cd: () => {
        return false
    }
}

interface 接口继承

interface Axxsxs extends B {
    name: string,
    age?: number, // 可选 
    readonly cd: () => boolean // 设置只读
}
interface B {
    id: string
}
let a: Axxsxs = {
    id: '1233',
    name: 'lx',
    age: 18,  // 可以写可以不写 
    cd: () => {
        return false
    }
}

interface 定义函数类型

interface Fn {
  // 参数name为string、返回值是 number类型的数组 
  (name:string): number[]
}
const fn:Fn = function(name:string) {
  return [1]
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值