diff --git a/docs/uts/_sidebar.md b/docs/uts/_sidebar.md index 24296210ed4cfd988ec239b501756724bf1c8651..9b2c8e161ed8a5aa7d988b497c7320c2d8830c6c 100644 --- a/docs/uts/_sidebar.md +++ b/docs/uts/_sidebar.md @@ -9,6 +9,7 @@ * [类class](class.md) * [接口interface](interface.md) * [类型兼容性](type-compatibility.md) +* [泛型](./generics.md) * [模块module](module.md) * 内置对象和 API * [Number](buildin-object-api/number.md) diff --git a/docs/uts/generics.md b/docs/uts/generics.md new file mode 100644 index 0000000000000000000000000000000000000000..9cdf189f9b1e32831a8ff1a255611ffa4326e102 --- /dev/null +++ b/docs/uts/generics.md @@ -0,0 +1,81 @@ +# 泛型(Generics) + +UTS 支持泛型(Generics)特性,允许您编写更通用、可重用的代码,同时提高类型安全性。 + +## 定义泛型 + +泛型使用尖括号 `<>` 声明一个或多个泛型参数。 + +## 泛型函数 + +泛型函数的泛型参数定义在函数参数的圆括号之前。 + +```ts +function test(arg: T): T { + return arg +} + +const str: string = test('a') + +const num: number = test(1) +``` + +## 泛型类 + +泛型类的泛型参数定义在类名之后。 + +```ts +class Test { + value: T + constructor (value: T) { + this.value = value + } +} + +const test1: Test = new Test('a') +const str1: string = test1.value + +const test2: Test = new Test(1) +const num1: number = test2.value +``` + +## 泛型接口 + +泛型接口与泛型类相似,泛型参数定义在接口名之后。 + +```ts +interface ITest { + value: T +} + +class TestImpl implements ITest { + value: T +} +``` + +## 泛型推断 + +当泛型参数类型与函数的参数类型相关时,泛型参数能够根据函数参数类型自动推断,此时可以省略泛型参数。 + +```ts +const str1 = test('a') +const str2 = test('a') +``` + +## 泛型约束 + +可以使用 `extends` 关键字来限制泛型参数的类型范围。 + +```ts +function testArray>(arg: T): T { + return arg +} +``` + +使用其他泛型类型时,如果不需要限制泛型参数的类型可以使用 `unknown` 关键字表示。 + +```ts +function testArray>(arg: T): T { + return arg +} +``` diff --git a/docs/uts/operator.md b/docs/uts/operator.md index 120f4bf53ebea75bdecab1e2b12b17ff3df14800..04ed5c2c549ac60b774582e090776fb323c7eba6 100644 --- a/docs/uts/operator.md +++ b/docs/uts/operator.md @@ -469,11 +469,11 @@ function fn(obj: any) { } ``` -包含泛型的类型,不能缺省泛型信息。如不需要判断具体的泛型类型,可以使用 `*` 表示任意泛型类型: +包含[泛型](./generics.md)的类型,不能缺省泛型信息。如不需要判断具体的泛型类型,可以使用 `unknown` 表示任意泛型类型: ```ts function fn(obj: any) { - if (obj instanceof Map<*, *>) { + if (obj instanceof Map) { // ... } }