TypeScript-interface接口类型

发布于:2024-05-24 ⋅ 阅读:(196) ⋅ 点赞:(0)

interface接口类型

在TS中使用interface接口来描述对象数据的类型,常用于给对象的属性和方法添加类型约束

⚠️ 一旦注解接口类型之后对象的属性和方法类型都需要满足要求,属性不能多也不能少

interface Person {
  name: string
  age: number
}

const p: Person = {
  name: 'lily',
  age: 20
}

应用场景:

  • 前端向后端发送数据:收集表单对象数据时的类型校验

  • 前端使用后端数据:渲染后端对象数组列表时的智能提示

// 表单数据收集场景
interface LoginForm {
  username: string
  password: string
}

let formData: LoginForm = {
  username: 'hanna'
  password: '123456'
}
// 渲染后端列表场景
interface Goods {
  id: string
  price: number
}

let list:Goods[] = [
  {
    id:'01',
    price: 100
  }
]

list.forEach((item) => console.log(item.price))

接口的可选设置

通过对属性进行可选标注,赋值的时候该属性可以缺失,如果有值必须保证类型满足要求

interface Datas {
  type: string
  size?: string
}
// 不传
let data: Datas = {
  type:'sucess'
}

// 传值必须类型匹配
let data: Datas = {
  type:'sucess',
  size:'small'
}

接口的继承

使用 extends 实现接口继承,实现类型复用

// 原价商品类型
interface GoodsType {
  id: string
  price: number
}
// 打折商品类型
interface DisGoodsType {
  id: string
  price: number
  disPrice: number
}

// 使用extends
interface DisGoodsType extends GoodsType {
  disPrice: number
}

Demo:

{
  code:200,
  msg:'success',
  data: {
    title:'文章标题',
    content:'文章内容'
  }
}
interface Data {
  title: string
  content: string
}

interface ResData {
  code: number
  msg: string
  data: Data
}

let res: ResData = {
  code: 200,
  msg:'success',
  data:{
    title:'标题',
    content:'内容'
  }
}

网站公告

今日签到

点亮在社区的每一天
去签到