TypeSript2 接口类型interface

接口对象的类型

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

主要是以下特性

interface接口类型 常用于定义对象 比较两个对象形状是否一致

1.对比形状

//这样写是会报错的 因为我们在person定义了a,b但是对象里面缺少b属性

//使用接口约束的时候不能多一个属性也不能少一个属性

//必须与接口保持一致

interface Person {

b:string,

a:string

}

const person:Person = {

a:"213"

}

2. 重合

interface face1 {

name: string;

}

interface face1 {

age: number;

}

let a1: face1 = {

name: "xx",

age: 20,

}

3. 任意key 索引签名propName: string: any; 不确定后端会传是什么类型 最好使用any

interface face1 {

name: string;

propName: string: any;

}

let a5: face1 = {

name: "xx",

age: 20,

c: 123,

};

3 ? readeOnly ?是可选的后端可能不传这个值 readeOnly是只读不能改常用于后端的id 及函数

interface face1 {

name: string;

age?: number;

readonly id:number

readonly cb:()=>boolean

}

let a1: face1 = {

id:1,

name: "xx",

cb:()=>{

return false

}

}

a1.cb=()=>{ // 函数被修改了 不期望被修改

return true

}

4 接口继承 extends

interface face1 extends face2 {

name: string;

}

interface face2 {

age: number;

}

let a1: face1 = {

name: "xx",

age: 20,

};

5 接口定义函数类型

interface Person {

b?: string,

readonly a: string,

propName: string: any;

cb:()=>void

}

const person: Person = {

a: "213",

c: "123",

cb:()=>{

console.log(123)

}

}

TypeSript3 数组类型-CSDN博客

相关推荐
gis开发之家6 小时前
《Vue3 从入门到大神40篇》Vue3 源码详解(十):diff 算法全解析 —— 为什么 Vue3 比 Vue2 更快?
javascript·算法·typescript·前端框架·vue3·vue3源码
GitLqr9 小时前
提升 Web 开发效率:我常用的 10 个 TypeScript 实战技巧
vue.js·react.js·typescript
勇往直前plus11 小时前
Vue3(篇四)单页面应用到路由管理
javascript·typescript·前端框架·vue
勇往直前plus12 小时前
Vue3(篇三) Element Plus
前端·javascript·typescript·vue
退休倒计时13 小时前
【每日一题】LeetCode 207. 课程表 TypeScript
算法·leetcode·typescript
lincats16 小时前
Remotion Skill vs HyperFrames Skill:AI视频圈两大技能包正面交锋,最好的对手,最好的搭档?
typescript·vibe coding·claude code·skills
Web4Browser1 天前
指纹浏览器 API 自动化怎么接:启动 Profile、获取 CDP 端点并连接自动化框架
前端·网络·typescript·自动化
寒水馨1 天前
Linux下载、安装 Bun v1.3.14(附安装包bun-linux-x64.zip)
linux·javascript·typescript·node.js·bun·运行时·包管理器
退休倒计时1 天前
【复习】LeetCode 二叉树DFS TypeScript
算法·leetcode·typescript·深度优先
用户0934077735142 天前
HarmonyOS WPS Open SDK 二开周回顾:从注册到关窗回传怎么串
typescript·harmonyos