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

相关推荐
用户938515635071 天前
TypeScript 高级类型 + CSS 三列布局:从类型体操到样式工程的进阶之路
css·面试·typescript
moMo1 天前
深入 NestJS:从工厂模式到装饰器模式的架构之美
typescript·nestjs
烬羽2 天前
NestJS 依赖注入:Controller 里那个没有 new 的 service,到底从哪来的?
设计模式·typescript·nestjs
渣波2 天前
NestJS 企业级后端架构实战:从核心代码到工程化思维的深度重构
前端·typescript·nestjs
嘟嘟07172 天前
NestJS 入门:从 NestFactory 入口到 Module/Controller/Service 模块化结构一次讲清
typescript·node.js·nestjs
用户938515635072 天前
实战 Todo CRUD —— 从路由到异常,手写一个完整模块
后端·typescript·nestjs
不知疲倦的老鸟3 天前
Next.js 15 多语言站点的 6 个坑:从 query string 路由到 URL 路径
typescript·next.js
北墨NoLimit3 天前
鸿蒙线程间通信怎么选:TaskPool、TaskGroup、LongTask 与 Worker 实战
typescript·harmonyos
Orange_sparkle3 天前
从五个 TypeScript 文件看懂 Coding Agent:一次 nano-pi 学习复盘
javascript·学习·typescript
深海鱼在掘金3 天前
深入浅出RAG——第7章:基础篇实战:文档问答机器人
人工智能·typescript·命令行