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])
相关推荐
2301_801074152 分钟前
TypeScript异常处理
前端·javascript·typescript
下雪天的夏风3 小时前
TS - tsconfig.json 和 tsconfig.node.json 的关系,如何在TS 中使用 JS 不报错
前端·javascript·typescript
天下无贼!17 小时前
2024年最新版TypeScript学习笔记——泛型、接口、枚举、自定义类型等知识点
前端·javascript·vue.js·笔记·学习·typescript·html
Jorah3 天前
1. TypeScript基本语法
javascript·ubuntu·typescript
小白小白从不日白4 天前
TS axios封装
前端·typescript
aimmon4 天前
Superset二次开发之源码DependencyList.tsx 分析
前端·typescript·二次开发·bi·superset
下雪天的夏风5 天前
Vant 按需引入导致 Typescript,eslint 报错问题
前端·typescript·eslint
theMuseCatcher5 天前
Vue3+TypeScript+Vite+Less 开发 H5 项目(amfe-flexible + postcss-pxtorem)
typescript·less·postcss
Qiyandays5 天前
vue + Lodop 制作可视化设计页面 实现打印设计功能(四)
前端·vue.js·typescript
人工智能的苟富贵6 天前
微信小程序中的模块化、组件化开发:完整指南
微信小程序·小程序·typescript