搜索
首页web前端js教程如何开发通用类

如何开发通用类

在开发实际的泛型类之前,我们先来了解一下Generic类。称为泛型的 TypeScript 类可以处理多种类型的数据。它是各种参数,并使用尖括号 () 显示。这代表了该类将用于实现此目的的数据类型。然后可以在类的属性和函数中使用类型参数,以使类灵活并可与其他数据类型重用。

我们将做一些简报。假设在示例中,类型参数被表示为“T”并且简单泛型类“MyGenericClass”的属性“value”被表示。 “T”和“价值”都可以被创造。如果此类使用替代类型(例如“数字”或“字符串”)实例化,则“值”属性将具有适当的类型。

由于同一个类可以与多种数据类型一起使用,这为您的代码提供了额外的灵活性和重用性。您还可以使用约束来限制用作类型参数的种类。

语法

在 TypeScript 中创建泛型类的语法如下 -

class ClassName<TypeParameter> {
   // class properties and methods
}

其中“ClassName”是类的名称,“TypeParameter”是该类将使用的数据类型的占位符。

示例 1

此示例演示如何使用 TypeScript 中的泛型类来创建可处理多种数据类型的类。该类使用类型参数 T 进行定义,该参数用于该类的属性和方法中,从而允许该类灵活且可重用不同类型的数据。 “Queue”类有一个名为“data”的私有属性,它是一个 T 类型的数组。

该类还具有三个方法:“enqueue”,将项目添加到队列末尾;“dequeue”,从队列前面删除项目;“peek”,返回队列中的项目。队列前面而不删除它。我们创建了 Queue 类的两个实例,一个用于数字,另一个用于字符串。该类可以处理不同的数据类型,使我们的代码更加灵活和可重用。

class Queue<T> {
   private data: T[] = []

   // add an item to the end of the queue
   enqueue(item: T) {
      this.data.push(item)
   }

   // remove an item from the front of the queue
   dequeue(): T | undefined {
      return this.data.shift()
   }

   // get the item at the front of the queue
   peek(): T | undefined {
      return this.data[0]
   }
}
let numberQueue = new Queue<number>()
numberQueue.enqueue(1)
numberQueue.enqueue(2)
console.log(numberQueue.peek())
console.log(numberQueue.dequeue())
console.log(numberQueue.peek())

let stringQueue = new Queue<string>()
stringQueue.enqueue('Hello')
stringQueue.enqueue('world')
console.log(stringQueue.peek())
console.log(stringQueue.dequeue())
console.log(stringQueue.peek())

编译时,它将生成以下 JavaScript 代码。

var Queue = /** @class */ (function () {
   function Queue() {
      this.data = [];
   }
   // add an item to the end of the queue
   Queue.prototype.enqueue = function (item) {
      this.data.push(item);
   };
   // remove an item from the front of the queue
   Queue.prototype.dequeue = function () {
      return this.data.shift();
   };
   // get the item at the front of the queue
   Queue.prototype.peek = function () {
      return this.data[0];
   };
   return Queue;
}());
var numberQueue = new Queue();
numberQueue.enqueue(1);
numberQueue.enqueue(2);
console.log(numberQueue.peek());
console.log(numberQueue.dequeue());
console.log(numberQueue.peek());
var stringQueue = new Queue();
stringQueue.enqueue('Hello');
stringQueue.enqueue('world');
console.log(stringQueue.peek());
console.log(stringQueue.dequeue());
console.log(stringQueue.peek());

输出

上述代码将产生以下输出 -

1
1
2
Hello
Hello
world

示例 2

在此示例中,我们将开发另一个具有两种泛型类型属性的泛型类。 “KeyValuePair”类有两个私有属性,“key”和“value”,分别为 T 类型和 U 类型。该类还有两个方法“getKey”和“getValue”,分别返回键和值属性。

该类可以使用数据类型(例如数字、字符串或对象)实例化键和值。我们创建了 KeyValuePair 类的两个实例,一个以字符串作为键,数字作为值,另一个以字符串作为键,对象作为值。该类可以使用不同的数据类型作为键和值,使我们的代码更加灵活和可重用。

class KeyValuePair<T, U> {
   private key: T
   private value: U

   constructor(key: T, value: U) {
      this.key = key
      this.value = value
   }

   // method to get the key
   getKey(): T {
      return this.key
   }

   // method to get the value
   getValue(): U {
      return this.value
   }
}

let numberKeyValuePair = new KeyValuePair<string, number>('age', 20)
console.log(numberKeyValuePair.getKey()) // "age"
console.log(numberKeyValuePair.getValue()) // 20

let objectKeyValuePair = new KeyValuePair<string, object>('person', {
   name: 'Tutorialspoint',
   age: 10,
})
console.log(objectKeyValuePair.getKey()) // "person"
console.log(objectKeyValuePair.getValue()) // {name: "Tutorialspoint", age: 10}

编译时,它将生成以下 JavaScript 代码。

var KeyValuePair = /** @class */ (function () {
   function KeyValuePair(key, value) {
      this.key = key;
      this.value = value;
   }
   // method to get the key
   KeyValuePair.prototype.getKey = function () {
      return this.key;
   };
   // method to get the value
   KeyValuePair.prototype.getValue = function () {
      return this.value;
   };
   return KeyValuePair;
}());
var numberKeyValuePair = new KeyValuePair('age', 20);
console.log(numberKeyValuePair.getKey()); // "age"
console.log(numberKeyValuePair.getValue()); // 20
var objectKeyValuePair = new KeyValuePair('person', {
   name: 'Tutorialspoint',
   age: 10
});
console.log(objectKeyValuePair.getKey()); // "person"
console.log(objectKeyValuePair.getValue()); // {name: "Tutorialspoint", age: 10}

输出

上述代码将产生以下输出 -

age
20
person
{ name: 'Tutorialspoint', age: 10 }

在 TypeScript 中使用泛型类可以生成更灵活、可重用且可维护的代码。此外,TypeScript 的类型检查系统可确保泛型类中使用的类型在编译时正确使用,从而进一步提高代码的整体质量和安全性。泛型类是 TypeScript 的一项强大功能,可用于编写更可靠和可重用的代码。

以上是如何开发通用类的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
在JavaScript中替换字符串字符在JavaScript中替换字符串字符Mar 11, 2025 am 12:07 AM

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

jQuery检查日期是否有效jQuery检查日期是否有效Mar 01, 2025 am 08:51 AM

简单JavaScript函数用于检查日期是否有效。 function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //测试 var

jQuery获取元素填充/保证金jQuery获取元素填充/保证金Mar 01, 2025 am 08:53 AM

本文探讨如何使用 jQuery 获取和设置 DOM 元素的内边距和外边距值,特别是元素外边距和内边距的具体位置。虽然可以使用 CSS 设置元素的内边距和外边距,但获取准确的值可能会比较棘手。 // 设置 $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); 你可能会认为这段代码很

10个jQuery手风琴选项卡10个jQuery手风琴选项卡Mar 01, 2025 am 01:34 AM

本文探讨了十个特殊的jQuery选项卡和手风琴。 选项卡和手风琴之间的关键区别在于其内容面板的显示和隐藏方式。让我们深入研究这十个示例。 相关文章:10个jQuery选项卡插件

10值得检查jQuery插件10值得检查jQuery插件Mar 01, 2025 am 01:29 AM

发现十个杰出的jQuery插件,以提升您的网站的活力和视觉吸引力!这个精选的收藏品提供了不同的功能,从图像动画到交互式画廊。让我们探索这些强大的工具: 相关文章: 1

HTTP与节点和HTTP-Console调试HTTP与节点和HTTP-Console调试Mar 01, 2025 am 01:37 AM

HTTP-Console是一个节点模块,可为您提供用于执行HTTP命令的命令行接口。不管您是否针对Web服务器,Web Serv

自定义Google搜索API设置教程自定义Google搜索API设置教程Mar 04, 2025 am 01:06 AM

本教程向您展示了如何将自定义的Google搜索API集成到您的博客或网站中,提供了比标准WordPress主题搜索功能更精致的搜索体验。 令人惊讶的是简单!您将能够将搜索限制为Y

jQuery添加卷轴到DivjQuery添加卷轴到DivMar 01, 2025 am 01:30 AM

当div内容超出容器元素区域时,以下jQuery代码片段可用于添加滚动条。 (无演示,请直接复制到Firebug中) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具