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

相关推荐
console.log('npc')1 小时前
从0到1实现任务评价统计功能:React + TypeScript 实战指南(小白注释版)
前端·react.js·typescript
ZoeLandia1 小时前
React04:事件处理与受控表单
开发语言·前端·react.js·typescript
ZoeLandia2 小时前
React05:useEffect 与副作用
开发语言·前端·react.js·typescript
Flynt15 小时前
Cloudflare 用 Rust 重写了 TypeScript:我拿同一批代码跑了跑,报错一模一样,退出码不一样
rust·typescript·前端工程化
落花看风雪15 小时前
从零开始搭建后台系统(vue3+TypeScript+Vite)01
typescript·vue·js
行者全栈架构师20 小时前
我让 AI 独立开发了一款游戏:零依赖、188 个测试全绿、工期压到四分之一
typescript·canvas·vibecoding
Eyfcom21 小时前
〖深度〗鸿蒙 ArkTS 移动应用开发经验:从 TypeScript 心智模型到声明式运行时的六层认知重构
typescript·移动开发·harmonyos·arkts
Patrick_Wilson2 天前
悬浮提示从哪来:LSP、tsserver 与 .d.ts
typescript·npm·前端工程化
oldnicke3 天前
理解 TRAE 的 Agent + IDE 思路:用一个 Markdown 检查器拆解完整交付
typescript
钱栈up3 天前
GitHub 热榜实测|REA:用 Agent 逆向一切
typescript·开源·github