前端 TS 快速入门之二:接口

1. 接口有什么用

通过 interface 定义接口。

检测对象的属性,不会去检查属性的顺序,只要相应的属性存在并且类型也是对的就可以。

javascript 复制代码
interface IPerson {
  name: string;
  age: number;
}
function say(person: IPerson): void {
  console.log(`my name is ${person.name}, and age is ${person.age}`);
}
let me = {
  name: "funlee",
  age: 18,
};
say(me); // my name is funlee, and age is 18

2. 可选属性

属性后面加一个 ? 符号,表示该属性可选。

javascript 复制代码
interface IPerson {
  name: string;
  age: number;
  // love 可选
  love?: string;
}

3. 只读属性

属性名前加 readonly,表示该属性只读。

javascript 复制代码
interface IPerson {
  // name 只读
  readonly name: string;
  age: number;
  love?: string;
}
let me: IPerson = {
  name: "funlee",
  age: 18,
};
// name 不允许被赋值
me.name = "new name"; // error!

4. 函数接口

接口可以描述函数类型,它定义了函数的参数列表和返回值类型,参数列表里的每个参数都需要名字和类型,函数的参数名不需要与接口里定义的名字相匹配,只需要类型兼容就可以了。

javascript 复制代码
interface GetArea {
  (width: number, height: number): number;
}
let getArea: GetArea = function (w: number, h: number) {
  return w * h;
};
getArea(5, 6); // 30

5. 继承接口

一个接口可以继承多个接口,创建出多个接口的合成接口,如:

javascript 复制代码
interface Shape {
  color: string;
}
interface PenStroke {
  penWidth: number;
}
interface Square extends Shape, PenStroke {
  sideLength;
}
const square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;

6. 混合类型

让对象同时作为函数和对象使用,并带有额外的属性,如:

javascript 复制代码
interface MixedDemo {
  (str: string): void;
  defaultStr: string;
}

function foo(): MixedDemo {
  let x = <MixedDemo>function (str: string) {
    console.log(str);
  };
  x.defaultStr = "Hello, world";
  return x;
}

let c = foo();
c("This is a function"); // 'This is a function'
c.defaultStr; // 'Hello, world'
相关推荐
萌萌哒草头将军3 分钟前
绿联云 NAS 安装 AudioDock 详细教程
前端·docker·容器
贺今宵21 分钟前
安装better-sqlite3报错electron-vite
javascript·sql·sqlite·sqlite3
GIS之路35 分钟前
GIS 数据转换:使用 GDAL 将 GeoJSON 转换为 Shp 数据
前端
2501_944446001 小时前
Flutter&OpenHarmony文件夹管理功能实现
android·javascript·flutter
朴shu1 小时前
Luckysheet 远程搜索下拉 控件开发 : 揭秘二开全流程
前端
MediaTea2 小时前
Python:模块 __dict__ 详解
开发语言·前端·数据库·python
字节跳动开源3 小时前
Midscene v1.0 发布 - 视觉驱动,UI 自动化体验跃迁
前端·人工智能·客户端
光影少年3 小时前
三维前端需要会哪些东西
前端·webgl
王林不想说话3 小时前
React自定义Hooks
前端·react.js·typescript
颜酱4 小时前
滑动窗口详解:原理+分类+场景+模板+例题(视频贼清晰)
javascript