TypeScript中的接口(interface )详解

文章目录

在TypeScript中,接口(interface )被用来定义自定义数据类型,这有助于我们在开发过程中对对象进行描述。接口可以包含属性和方法的声明,但不提供实现。让我们一起来了解接口在TypeScript中的应用。

一、定义接口

type和interface 都可以用来定义对象,但我们一般采用interface来定义

javascript 复制代码
interface Person {
  name: string;
  age: number;
}

let person: Person = {
  name: "qiyan",
  age: 30
};

上述代码中,我们定义了一个名为Person的接口,它具有name和age两个属性。然后,我们创建了一个符合该接口的对象并进行了赋值。

二、可选属性

接口中的属性可以标记为可选的,在创建对象时就可以选择性地包含这些属性。使用即可实现

javascript 复制代码
interface Person {
  name: string;
  age?: number;
}

let person: Person = {
  name: "qiyan",
};

针对于可选属性,像后端有些参数可传可不传过来时,我们就可以采用该方式

三、只读属性

接口中的属性也可以标记为只读,这意味着一旦对象被创建后,这些属性的值将不能被改变。

javascript 复制代码
interface Person {
  readonly name: string;
  age: number;
}

let person: Person = {
  name: "qiyan",
  age:18
};

person.name='xigua';   //错误,不能进行修改

四、函数类型

接口不仅可以描述对象,还可以描述函数类型。

javascript 复制代码
interface Person {
    (name:string,age?:number):void
}
const person:Person = (name:string,age:number=18)=>{
    console.log(`我是${name},我今年${age}岁啦`)
}
person('qiyan')

五、继承接口

接口可以继承其他接口,从而使得一个接口可以拥有另一个接口的所有成员。其关键字为extends

javascript 复制代码
interface Animal{
    name:string,
    age:number,
    
}
interface Cat extends Animal{
    sex:number
}

const cat:Cat = {
    name:'xixi',
    age:3,
    sex:0
}

六、索引签名

索引签名可定义具有动态属性的对象结构
索引签名语法

javascript 复制代码
interface Person{
   [key:string]:any
    
}
const person:Person = {
    name:'qiyan',
    age:18
}

只读索引签名

javascript 复制代码
interface Person{
   readonly [key:string]:any
    
}

const person:Person = {
    name:'qiyan',
    age:18
}
person.name= 'xigua'  //报错,不能修改

七、函数重载

根据传入的参数类型和数量的不同,选择执行不同的函数实现

javascript 复制代码
interface Fn{
    (ids:number | number[]):void;
}
const fn:Fn = (ids:number | number[]):void{
    if(typeof ids == 'number'){
        //执行只传一个值的操作
    }else if(Array.isArray(ids)){
        //执行传数组的操作
    }
}
fn(1)
fn([1,2,3])
相关推荐
guangzan4 小时前
DeepSeek-Lane:在 Cursor 内使用 DeepSeek V4 模型
typescript
晓杰'9 小时前
从0到1实现 Balatro 游戏后端(1):项目规划与牌型判断实现
后端·websocket·typescript·node.js·游戏开发·项目实战·nestjs
Forget the Dream11 小时前
基于适配器模式的 Axios 封装实践
设计模式·typescript·axios·适配器模式
烛衔溟1 天前
TypeScript 接口继承与混合类型
linux·ubuntu·typescript
送鱼的老默1 天前
学习笔记--入门typescript直接案例开搞
前端·typescript
spmcor1 天前
TypeScript 中 null 与 undefined 的区别 —— 一篇彻底搞懂的指南
typescript
烛衔溟1 天前
TypeScript 接口实战 —— 处理复杂嵌套对象
linux·ubuntu·typescript
求学中--2 天前
ArkUI电商首页完整实战
华为·typescript·harmonyos
布局呆星3 天前
Spring Boot+MyBatis-Plus+Vue3前后端协作Note
spring boot·typescript·vue·mybatis
漫游的渔夫3 天前
前端开发者做 AI Agent:别只渲染答案,用 7 个状态接住确认、错误和 trace
前端·人工智能·typescript