前端 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'
相关推荐
小飞侠在吗1 天前
vue props
前端·javascript·vue.js
DsirNg1 天前
页面栈溢出问题修复总结
前端·微信小程序
小徐_23331 天前
uni-app 也能远程调试?使用 PageSpy 打开调试的新大门!
前端·微信小程序·uni-app
大怪v1 天前
【Virtual World 03】上帝之手
前端·javascript
DXDZ20221 天前
0526P,CSL05U6U USB3.0静电防护阵列
typescript·intellij-idea·推荐算法
招来红月1 天前
记录JS 实用API
javascript
别叫我->学废了->lol在线等1 天前
演示 hasattr 和 ** 解包操作符
开发语言·前端·python
霍夫曼1 天前
UTC时间与本地时间转换问题
java·linux·服务器·前端·javascript
DARLING Zero two♡1 天前
浏览器里跑 AI 语音转写?Whisper Web + cpolar让本地服务跑遍全网
前端·人工智能·whisper
꒰ঌ小武໒꒱1 天前
文件上传全维度知识体系:从基础原理到高级优化
javascript·node.js