当前位置: 代码网 > it编程>编程语言>Javascript > TypeScript中的接口和泛型你了解吗

TypeScript中的接口和泛型你了解吗

2024年05月19日 Javascript 我要评论
接口使用 interface 关键字来定义数据类型对象类型当存在于较长的数据类型约束时,我们可以通过 type 关键字 为类型注解起别名,也可以通过接口来定义type usertype = { nam

接口

使用 interface 关键字来定义数据类型

对象类型

当存在于较长的数据类型约束时,我们可以通过 type 关键字 为类型注解起别名,也可以通过接口来定义

type usertype = { name: string; age?: number };
const user: usertype = {
  name: "kiki",
  age: 18,
};
interface iusertype { name: string; age?: number }
const person: iusertype = {
  name: 'alice',
  age: 20
}

索引类型

interface 和type定义对象都可以为只知道key的类型,不知道具体 key 值的时候,进行类型的定义

interface ilanguage {
  [index: number]: string;
}
const language: ilanguage = {
  0: "html",
  1: "css",
  2: "js",
};
type score = {
  [name: string]: number;
}
const score: score = {
  chinese: 120,
  math: 95,
  englist: 88,
};

函数类型

定义函数时,interface 和 type 的语法稍有不同

interface iselftype {
  (arg: string): string;
}
type logtype = (arg: string) => string;
function print(arg: string, fn: iselftype, logfn: logtype) {
  fn(arg);
  logfn(arg);
}
function self(arg: string) {
  return arg;
}
console.log(print("hello", self, self));

继承

接口可以实现多继承,继承后的接口具备所有父类的类型注解

interface iswim {
  swimming: () => void;
}
interface ieat {
  eating: () => void;
}
interface ibird extends iswim, ieat {}
const bird: ibird = {
  swimming() {},
  eating() {},
};

交叉类型

交叉类型其实是与的操作,用 & 符号,将接口进行与操作后,实质上需要满足所有与操作接口的类型注解

interface iswim {
  swimming: () => void;
}
interface ieat {
  eating: () => void;
}
type fish = iswim | ieat;
type bird = iswim & ieat;
const fish: fish = {
  swimming() {},
};
const bird: bird = {
  swimming() {},
  eating() {},
};
export {}

接口实现

接口可以通过类使用 implements 关键字来实现,类只能继承一个父类,但是可以实现多个接口

interface iswim {
  swimming: () => void
}
interface ieat {
  eating: () => void
}
class animal {}
class fish extends animal implements iswim, ieat {
  swimming(){}
  eating(){}
}
class person implements iswim {
  swimming(){}
}
function swimaction(iswim: iswim){
  iswim.swimming()
}
swimaction(new fish())
swimaction(new person())

没有实现接口的类,自然是没有该接口中的方法

在这里插入图片描述

interface 和 type 的区别

很多时候 interface 和 type 是相同的,但有一个明显区别在于 interface 可以重复定义,类型注解会累加,而 type 重复定义会报错

在这里插入图片描述

字面量赋值

直接把字面量赋值类型给变量时,会对字面量进行类型推导,多出的属性会报错

在这里插入图片描述

但是将对象的引用赋值的话,会进行 freshness 擦除操作,类型检测时将多余的属性擦除,如果依然满足类型就可以赋值

在这里插入图片描述

枚举类型

枚举类型通过 enum 关键字来定义,它和联合类型实现的功能类似,但是枚举类型的代码阅读性会更强一些

enum direction {
  left,
  right,
  top,
  bottom,
}
function turndirection(direction: direction) {
  switch (direction) {
    case direction.left:
      break;
    case direction.right:
      break;
    case direction.top:
      break;
    case direction.bottom:
      break;
    default:
      const foo: never = direction;
      break;
  }
}
turndirection(direction.left);

泛型

泛型函数

当不确定入参的类型时,可以定义类型注解为泛型,使用的时候再指定具体类型,使用 <> 来进行泛型的定义。

function self<t>(element: t) {
  return element;
}
self<string>("alice");
self<number>(2);
self<null>(null);

如果没有定义类型,ts会进行类型推导,有可能并不是我们希望的类型,如以下字符串推导出来不是”string“字符串类型,而是“hello”字面量类型。

在这里插入图片描述

当存在多个参数时,在泛型中定义多个即可

function foo<t, e, o>(a: t, b: e, c: o){}
foo(1, 'alice', false)
foo(['alice'], undefined, null)

泛型接口

在接口中使用泛型,将类型注解写在接口名后

interface person<t, e> {
  name: t;
  age: e;
}
const person: person<string, number> = {
  name: "alice",
  age: 20,
};

在接口中使用泛型是无法进行类型推导的,使用的时候必须指定具体的类型

在这里插入图片描述

除非在接口定义的时候给泛型设置了默认值

interface book<t = string, e = number> {
  category: t;
  price: e;
}
const book: book = {
  category: "nature",
  price: 88.6,
};
const dictionary: book<number, string> = {
  category: 1,
  price: '88'
}

泛型类

类中定义的方式,只是将具体的数据类型替换成了泛型,在类中是可以进行类型推导的

class point<t> {
  x: t;
  y: t;
  z: t;
  constructor(x: t, y: t, z: t) {
    this.x = x;
    this.y = y;
    this.z = z;
  }
}
new point("1.55", "2.34", "3.67");
new point(1.55, 2.34, 3.67);

类型约束

泛型可以通过继承来进行类型约束

只需要传入的参数满足泛型的条件,即有 length 属性

interface ilength {
  length: number;
}
function getlength<t extends ilength>(element: t) {
  return element.length;
}
getlength("alice");
getlength(["alice", "kiki", "lucy"]);
getlength({ length: 5 });

接口、枚举、泛型 这些类型在javascript都是没有的,但在typescirpt中都是非常重要的类型注解。

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注代码网的更多内容!    

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com