【前端vue3】TypeScrip-interface(接口)和对象类型

对象类型

定义对象需要用到interface(接口),主要用来约束数据的类型满足格式

定义方式如下:

javascript 复制代码
interface Person {
    name: string;
    age: number;
}

如对象中与接口中的属性不一致会报错,必须保持一致

例如如下:

javascript 复制代码
interface Person {
    name: string;
    age: number;
}

const person: Person = {
    name:"小C学安全"
}
//会提示类型 "{ name: string; }" 中缺少属性 "age",但类型 "Person" 中需要该属性。ts(2741)

接口的重合和继承

重合interface,可以合并两个相同对象名的属性

例如:

javascript 复制代码
interface Person {
    name: string;
}
interface Person {
    age: number;
}
const person: Person = {
    name:"小C学安全",
    age: 20
}

继承interface,例如对象A可以继承对象B的属性

例如:

javascript 复制代码
interface PersonA {
    name: string;
}
interface PersonB extends PersonA {
    age: number;
}
const person: PersonB = {
    name:"小C学安全",
    age: 20
}

可选属性

可选属性就是该属性是可以不存在的

例如:

javascript 复制代码
interface PersonA {
    name: string;
    age?: number;
}

const person: PersonA = {
    name:"小C学安全",
}
//这样写是不会报错的

也可以这么写
interface PersonA {
    name: string;
    age?: number;

}

const person: PersonA = {
    name:"小C学安全",
    age: 20
}

任意属性

定义方式: [propName: string]

javascript 复制代码
interface PersonA {
    name: string;
    age?: number; //定义可选属性
    [propName: string]:any; //定义任意属性

}

const person: PersonA = {
    name:"小C学安全",
    age: 20,
    city: "北京"
}

以上代码中,PersonA并没有定义属性city,但是代码没有报错,是因为我们定义了任意属性

只读属性

只读属性是只能读取,但是不允许被赋值修改的

定义方式:在属性前加上readonly

例如:

javascript 复制代码
interface PersonA {
    readonly name: string;
    age?: number; //定义可选属性
    [propName: string]:any; //定义任意属性


}

const person: PersonA = {
    name:"小C学安全",
    age: 20,
    city: "北京"
}

person.name= "小白"

以上代码就会报错,会提示:

无法为"name"赋值,因为它是只读属性。ts(2540)

添加函数

可以给对象属性添加函数

例如:

javascript 复制代码
interface PersonA {
    readonly name: string;
    age?: number; //定义可选属性
    [propName: string]:any; //定义任意属性
    test : ()=>void; // 定义函数
}

const person: PersonA = {
    name:"小C学安全",
    age: 20,
    city: "北京",
    test: ()=>{
        console.log("定义函数成功")
    }
}

person.test()
相关推荐
BillKu2 小时前
Vue3 + Element-Plus 抽屉关闭按钮居中
前端·javascript·vue.js
面向星辰3 小时前
html中css的四种定位方式
前端·css·html
Async Cipher3 小时前
CSS 权重(优先级规则)
前端·css
大怪v3 小时前
前端佬:机器学习?我也会啊!😎😎😎手“摸”手教你做个”自动驾驶“~
前端·javascript·机器学习
Liquad Li4 小时前
Angular 面试题及详细答案
前端·angular·angular.js
用户21411832636024 小时前
首发!即梦 4.0 接口开发全攻略:AI 辅助零代码实现,开源 + Docker 部署,小白也能上手
前端
gnip6 小时前
链式调用和延迟执行
前端·javascript
SoaringHeart6 小时前
Flutter组件封装:页面点击事件拦截
前端·flutter
杨天天.6 小时前
小程序原生实现音频播放器,下一首上一首切换,拖动进度条等功能
前端·javascript·小程序·音视频
Dragon Wu6 小时前
React state在setInterval里未获取最新值的问题
前端·javascript·react.js·前端框架