温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

TypeScript中的接口和泛型是什么

发布时间:2022-03-16 13:33:47 来源:亿速云 阅读:125 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关TypeScript中的接口和泛型是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

接口

使用 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())

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

TypeScript中的接口和泛型是什么

interface 和 type 的区别

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

TypeScript中的接口和泛型是什么

字面量赋值

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

TypeScript中的接口和泛型是什么

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

TypeScript中的接口和泛型是什么

枚举类型

枚举类型通过 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”字面量类型。

TypeScript中的接口和泛型是什么

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

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,
};

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

TypeScript中的接口和泛型是什么

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

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中都是非常重要的类型注解。

感谢各位的阅读!关于“TypeScript中的接口和泛型是什么”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI