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博客

相关推荐
running up19 小时前
Vite 全面解析:特性、对比、实践及最新演进
javascript·typescript
xfq20 小时前
typescript泛型枚举以及NaN传染处理
前端·typescript
辛-夷1 天前
TS封装axios
前端·vue.js·typescript·vue·axios
大布布将军1 天前
⚡️ 后端工程师的护甲:TypeScript 进阶与数据建模
前端·javascript·程序人生·typescript·前端框架·node.js·改行学it
Hao_Harrision1 天前
50天50个小项目 (React19 + Tailwindcss V4) ✨ | DrawingApp(画板组件)
前端·react.js·typescript·tailwindcss·vite7
仅此,1 天前
前端接收了id字段,发送给后端就变了
java·前端·javascript·spring·typescript
ttod_qzstudio1 天前
DriveLerpControllerEditor开发总结:一个3D编辑器插值控制系统的实现
vue.js·typescript·编辑器·tdesign
雪域迷影1 天前
怎么将.ts文件转换成.js文件?
javascript·typescript·npm·tsc
narukeu1 天前
聊下 rewriteRelativeImportExtensions 这个 TypeScript 配置项
前端·javascript·typescript
Hao_Harrision2 天前
50天50个小项目 (React19 + Tailwindcss V4) ✨ | DragNDrop(拖拽占用组件)
前端·react.js·typescript·tailwindcss·vite7