TypeScript笔记---泛型

在定义函数或者类时,如果类型不明确就可以使用泛型。

1. 泛型的使用

  1. 在函数声明或者类声明时使用去定义泛型T:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    function fn<T>(a: T): T{
    return a;
    }

    class A<T>{
    constructor(a: T){
    this.a = a;
    }
    }
  2. 泛型可以使用多个:
    1
    2
    3
    function fn<T, K>(a: T, b: K): T{
    return a;
    }
  3. 可以对泛型做一些限制:
    1
    2
    3
    4
    5
    6
    interface Inter{
    length: number;
    }
    function fn<T implements Inter>(a: T): T{
    return a;
    }

    2. 练习

  4. 使用下面的命令生成配置文件
    1
    npm init -y
  5. 安装webpack相关依赖
    1
    npm i -D webpack webpack-cli typescript ts-loader html-webpack-plugin webpack-dev-server
  6. 配置webpack.config.js文件如下
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    const path = require('path');
    const HTMLWebpackPlugin = require('html-webpack-plugin');

    module.exports = {
    entry: "./src/index.ts",
    output: {
    path: path.resolve(__dirname, 'dist'),
    filename: "bundle.js"
    },
    module: {
    rules: [
    {
    test: /\.ts$/,
    use: 'ts-loader',
    exclude: /node-modules/
    }
    ]
    },
    plugins: [
    new HTMLWebpackPlugin({
    template: "./src/index.html"
    }),
    ]
    };
  7. 配置tsconfig.json文件如下
    1
    2
    3
    4
    5
    6
    7
    8
    {
    "compilerOptions": {
    "module": "es2015",
    "target": "es2015",
    "strict": true,
    "noEmitOnError": true
    }
    }
  8. 编辑index.ts
    1

打赏
  • © 2025 Aoxue
  • Hexo Theme Ayer by shenyu
    • PV:
    • UV:

请我喝杯咖啡吧~

支付宝
微信