泛型
泛型
| function echo(arg: any): any {
return arg
}
const result = echo(123)
|
| function echo(arg: any): any {
return arg
}
const result: string = echo(123)
|
| function echo<T>(arg: T): T {
return arg
}
const str: string = 'str'
const result = echo(str)
console.log(typeof result) // string
|
1
2
3
4
5
6
7
8
9
10
11
12 | function echo<T>(arg: T): T {
return arg
}
const result = echo('str')
console.log(typeof result)
const result2 = echo(123)
console.log(typeof result2)
const result3 = echo(true)
console.log(typeof result3)
// string
// number
// boolean
|
| function swap<T, U>(tuple: [T, U]) : [U, T] {
return [tuple[1], tuple[0]]
}
const result = swap(['string', 123])
|
约束泛型
| function echoWitharr<T>(arg: T[]): T[] {
console.log(arg.length)
return arg
}
const arrs = echoWitharr([1, 2, 3])
const arrs2 = echoWitharr('str') // error TS2345: Argument of type '"str"' is not assignable to parameter of type 'unknown[]'.
|
1
2
3
4
5
6
7
8
9
10
11
12
13 | interface IWithLength {
length: number
}
function echoWithlength<T extends IWithLength>(arg: T): T {
console.log(arg.length)
return arg
}
const str = echoWithlength('str')
const obj = echoWithlength({ length: 10, width: 10 })
const arr2 = echoWithlength([1, 2, 3])
echoWithlength(13) // error TS2345: Argument of type '13' is not assignable to parameter of type 'IWithLength'.
|
泛型在类和接口中的使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 | class Queue<T> {
private data = [];
push(item: T) {
return this.data.push(item)
}
pop(): T {
return this.data.shift()
}
}
const queue = new Queue<number>()
queue.push(1)
console.log(queue.pop().toFixed())
interface KeyPair<T, U> {
key: T
value: U
}
let kp1: KeyPair<number, string> = { key: 1, value: 'str' };
let kp2: KeyPair<string, number> = { key: 'string', value: 2 };
|
| let arr: number[] = [1, 2, 3]
let arrTwo: Array<number> = [2, 2, 3]
|
类型别名
| let sum: (x: number, y: number) => number
const result = sum(1, 2)
type PlusType = (x: number, y: number) => number
let sum2: PlusType
const result2 = sum(2, 3)
type StrOrNumber = string | number
let result3: StrOrNumber = '123'
result3 = 123
|
字面量
| const str: 'name' = 'name'
const number: 1 = 1
type Directons = 'Up' | 'Down' | 'Left' | 'Right'
let toWhere: Directons = 'Left'
|
交叉类型
| interface Iname {
name: string
}
type IPerson = Iname & { age: number }
let person: IPerson = { name: '123', age: 233 }
|
声明文件
https://www.typescriptlang.org/dt/search?search=
npm install --save @types/jquery
| import { Action } from 'redux'
jQuery('#id')
|
内置类型