DAY 15
1
Modern Web

# 強型闖入DenoLand[14] - 泛型的概念與實作

``````template <class myType>
myType GetMax (myType a, myType b) {
return (a>b?a:b);
}
``````

`template <class any_type>`
`T` 代表了任何型別或你宣告出來的 `class/struct`

`vector<int>`
`<>`中就是能填任何的 `型別/class/struct`

``````function createArray(length: number, value: any): Array<any> {
let result = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}

createArray(3, 'x'); // ['x', 'x', 'x']
``````

``````function createArray<T>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}

createArray<string>(3, 'x'); // ['x', 'x', 'x']
``````

``````function createArray(length: number, value: string): Array<string> {
let result: string[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
``````

``````createArray(3, 'x');
``````

``````createArray<number>(3, 5);
``````

## 在泛型中應用多個引數

``````function swap<T, U>(tuple: [T, U]): [U, T] {
return [tuple[1], tuple[0]];
}

swap([7, 'seven']); // ['seven', 7]
``````

10/2 更新：各位讀者可以參考 Day16

## 泛型約束

``````function loggingIdentity<T>(arg: T): T {
console.log(arg.length);
return arg;
}
``````

``````index.ts(2,19): error TS2339: Property 'length' does not exist on type 'T'.
``````

``````interface Lengthwise {
length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
``````

``````function loggingIdentity<T extends Lengthwise>(arg: T): T {
//...
}
``````

## 多引數的相互約束

``````function copyFields<T extends U, U>(target: T, source: U): T {
for (let id in source) {
target[id] = (<T>source)[id];
}
return target;
}

let x = { a: 1, b: 2, c: 3, d: 4 };

copyFields(x, { b: 10, d: 20 });
``````

U: 我有百萬存款。

T: 我不止有百萬存款，我還有 GTR 。

## 泛型介面

``````interface CreateArrayFunc {
<T>(length: number, value: T): Array<T>;
}

let createArray: CreateArrayFunc;
createArray = function<T>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}

createArray(3, 'x'); // ['x', 'x', 'x']
``````

``````let createArray: CreateArrayFunc<any>;
``````

``````interface CreateArrayFunc<T> {
(length: number, value: T): Array<T>;
}

let createArray: CreateArrayFunc<any>;
createArray = function<T>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}

createArray(3, 'x'); // ['x', 'x', 'x']
``````