基础使用:

    1. // 泛型
    2. function echo<T>(arg: T): T {
    3. return arg
    4. }
    5. const result = echo(123)
    6. // 定义占位符<T,U> 然后去使用
    7. function swap<T, U>(tuple: [T, U]): [U, T] {
    8. return [tuple[1], tuple[0]]
    9. }

    约束泛型:extends

    1. interface IWithLength {
    2. length: number
    3. }
    4. function echoWithLength<T extends IWithLength>(arg: T): T {
    5. console.log(arg.length)
    6. return arg
    7. }
    8. const echoLength = echoWithLength({ a: 1, length: 1 })
    9. const strLength = echoWithLength('1231')
    10. const arrLength = echoWithLength([1,2])
    11. //const numLength = echoWithLength(123) //报错了

    类的泛型

    1. class Queue<T>{
    2. private list = []
    3. push(item:T){
    4. return this.list.push(item)
    5. }
    6. pop():T{
    7. return this.list.shift()
    8. }
    9. }
    10. const queue1 = new Queue<number>()
    11. queue1.push(1)
    12. console.log(queue1.pop().toFixed())
    13. const queue2 = new Queue<string>()
    14. queue2.push('123asd')
    15. console.log(queue2.pop().length)

    接口泛型

    1. interface keyPair<T, U> {
    2. key: T,
    3. value: U
    4. }
    5. let kp1: keyPair<string, number> = { key: 'str', value: 1 }
    6. let kp2: keyPair<number, string> = { key: 123, value: "" }
    7. let arr1: number[] = [2, 3, 4]
    8. let arr2: Array<number> = [2, 3]
    9. interface Iplus {
    10. (num1: number, num2: number): number
    11. }
    12. function plus(num1: number, num2: number): number {
    13. return num1 + num2
    14. }
    15. const num3: Iplus = plus
    16. interface same<T> {
    17. (num1: T, num2: T): T
    18. }
    19. function add(num1: number, num2: number): number {
    20. return num1 + num2
    21. }
    22. function connect(num1: string, num2: string): string {
    23. return num1 + num2
    24. }
    25. const a:same<number> = add
    26. const b:same<string> = connect