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

相关推荐
@二进制10 小时前
vue3+vant4+ts出现页面空白?甚至在App.vue的<template></template>中随便输入都无法显示?
前端·vue.js·typescript
桂森滨10 小时前
Vue3+Pinia+Vite+TS 还原高性能外卖APP项目 4️⃣首页开发
前端·typescript·vue
samroom10 小时前
【鸿蒙应用开发 Dev ECO Studio 5.0版本】从0到1!从无到有!最全!计算器------按钮动画、滑动退格、中缀表达式转后缀表达式、UI设计
数据结构·ui·华为·typescript·harmonyos·鸿蒙
hong16168810 小时前
TypeScript类型断言
linux·javascript·typescript
落魄江湖行11 小时前
入门篇六 Nuxt4错误处理:给应用装个安全气囊
前端·typescript·nuxt4
kyriewen11 小时前
你的JS代码总在半夜崩溃?TypeScript来“上保险”了
前端·javascript·typescript
一只小阿乐14 小时前
TypeScript中的React开发
前端·javascript·typescript·react
俺不会敲代码啊啊啊15 小时前
封装 ECharts Hook 适配多种图表容器
前端·vue.js·typescript·echarts
jump_jump1 天前
用 3100 个数字造一台计算机
性能优化·架构·typescript
这是个栗子1 天前
TypeScript(三)
前端·javascript·typescript·react