当前位置: 首页 > article >正文

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


http://www.kler.cn/a/280494.html

相关文章:

  • C语言04--数组超详解
  • easypoi模板导出word多页导出加强版
  • pikachu靶场通关攻略(XSS)(1~10关)
  • 【AI绘画】Midjourney前置指令/settings设置详解
  • MyBatis使用递归查询来实现多级菜单的功能
  • 从黑神话悟空看中医养生,各位“天命人”中医养生不了解一下吗?
  • 考研资讯平台
  • Linux3-Linux用户和权限
  • [每日一练]重新格式化部门表(分组聚合的思考)
  • 实习手记(8):增删改查
  • redis 主从及哨兵搭建
  • C++11中的decltype关键字
  • 特殊类设计和类型转换
  • Golang反射:运行时类型检查与操作
  • 亲测分享:这个获客工具,精准又好用!
  • 《计算机网络期末复习知识点大全》
  • C++操作excel,即使函数设置了不备份,但保存后,excel依然会自动生成备份文件的原因分析,及如何来禁止自动备份
  • 10. Java 中的 HashSet 和 HashMap 有什么区别?
  • 模拟实现STL中的unordered_map和unordered_set
  • Android PopupWindow弹窗动态显示在View的上下方,