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

相关推荐
濮水大叔9 小时前
在大型 Vue 项目中,如何有效管理复杂的状态?“散装版” vs “套装版”
前端·vue.js·typescript
谷哥的小弟1 天前
TypeScript数组类型
javascript·typescript
退休倒计时1 天前
【每日一题】LeetCode 199. 二叉树的右视图 TypeScript
算法·leetcode·typescript
前端之虎陈随易2 天前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·vue.js·人工智能·typescript·node.js
后台开发者Ethan3 天前
类型分类、联合类型、交叉类型
typescript
鹰影473 天前
一款AI笔记助手和远程同步的markdown笔记idea-note
人工智能·笔记·rust·typescript·react
想你依然心痛3 天前
AtomCode 在前端开发中的实战体验:React + TypeScript 项目开发实录
前端·react.js·typescript
疯狂的魔鬼3 天前
精确计算容器剩余视口高度:useAutoContainerFullHeight 的工程实践
前端·css·typescript
后台开发者Ethan3 天前
类型与变量
开发语言·typescript
孤狼warrior3 天前
从冒泡到传送带流水线:一个3D沉浸式算法靶场,让思想的伟力改变世界
python·算法·typescript