|
1 | | -### 基本语法 |
| 1 | +### 概述 |
2 | 2 |
|
3 | 3 | ### 变量申明
|
4 | 4 | ```js
|
@@ -30,6 +30,51 @@ const point: Point = { x: 10, y: 20 }
|
30 | 30 | ```js
|
31 | 31 | type mathfunc = (a: number, b: number) => number
|
32 | 32 | const product: mathfunc = (a, b) => a * b
|
| 33 | +``` |
| 34 | + |
| 35 | +### 泛型 |
| 36 | +泛型的意义在于函数的重用性,我们希望组件不仅能够支持当前的数据类型,同时也能支持未来的数据类型 |
| 37 | + |
| 38 | +**为什么不用`any`呢?** |
| 39 | + |
| 40 | +使用 `any` 会丢失掉一些信息,我们无法确定返回值是什么类型 |
| 41 | +泛型可以保证入参跟返回值是相同类型的,它是一种特殊的变量,只用于表示类型而不是值 |
| 42 | + |
| 43 | +语法 `<T>(arg:T):T` 其中`T`为自定义变量,能前后对应就行 |
| 44 | + |
| 45 | +```js |
| 46 | +const hello : string = "Hello vue!" |
| 47 | +function say<T>(arg: T): T { |
| 48 | + return arg; |
| 49 | +} |
| 50 | +console.log(say(hello)) // Hello vue! |
| 51 | +``` |
| 52 | + |
| 53 | +#### 泛型约束 |
| 54 | +我们使用同样的例子,加了一个`console`,但是很不幸运,报错了,因为泛型无法保证每种类型都有`.length` 属性 |
| 55 | + |
| 56 | +```js |
| 57 | +const hello : string = "Hello vue!" |
| 58 | +function say<T>(arg: T): T { |
| 59 | + console.log(arg.length) // Property 'length' does not exist on type 'T'. |
| 60 | + return arg; |
| 61 | +} |
| 62 | +console.log(say(hello)) // Hello vue! |
| 63 | +``` |
| 64 | + |
| 65 | +从这里我们也又看出来一个跟`any`不同的地方,如果我们想要在约束层面上就结束战斗,我们需要定义一个接口来描述约束条件 |
| 66 | + |
| 67 | +```js |
| 68 | +interface Lengthwise { |
| 69 | + length: number; |
| 70 | +} |
| 71 | + |
| 72 | +function say<T extends Lengthwise>(arg: T): T { |
| 73 | + console.log(arg.length) |
| 74 | + return arg; |
| 75 | +} |
| 76 | +console.log(say(1)) // Argument of type '1' is not assignable to parameter of type 'Lengthwise'. |
| 77 | +console.log(say({value: 'hello vue!', length: 10})) // { value: 'hello vue!', length: 10 } |
| 78 | +``` |
| 79 | + |
33 | 80 |
|
34 | | -console.log(num, str, arr, set, map, sum(1, 2), product(2, 3), point) |
35 | | -``` |
|
0 commit comments