TypeScript 使用教程

文章目录

安装和环境搭建

基本类型

tsconfig.ts 文件配置选项

使用webpack打包ts

例子(贪吃蛇小游戏)

前言

        主要做一些学习笔记,查缺补漏

TypeScript是JavaScript的超集,具有可选的类型并可以编译为纯JavaScript。从技术上讲TypeScript就是具有静态类型的 JavaScript 。


提示:以下是本篇文章正文内容,下面案例可供参考

安装和环境搭建

全局安装:

npm install -g typescript

编译:

tsc hello.ts

运行后会生成一个hello.js文件,然后可以通过node启动这个js文件。

自动编译:

tsc hello.ts -w

所有文件编译:

必须添加配置文件:tsconfig.json,然后执行命令(默认是所有文件编译):

tsc

基本类型

类型例子描述
number1,-33,2.5任意数字
string'hi',"hi"任意字符串
booleantrue,false布尔值
字面量其本身限制变量的值就是该字面量的值
any*任意类型
unknown*类型安全的any
void空值(undefined)没有值(或undefined)
never没有值不能是任何值
object{name:'小明'}任意的JS对象
array[1,2,3]任意JS数组
tuple[4,5]元素,TS新增类型,固定长度数组
enumenum{A,B}枚举,TS中新增类型
// 字符串
let a: string = '1231';

// 字面量,或者是male | 或者是feamle(联合类型)
let b: "male" | "female";
let c: boolean | string;

// any 表示任意类型,设置any后相当于关闭了TS的类型检测(不建议)
// 声明变量如果不指定类型,默认any,隐式any
let d: any;
d = 10;
d = 'hello';

// 未知类型的值
let e: unknown;

// 类型断言,告诉解析器变量的实际类型
e = a as string;
e = <string>a;

// void 表示空,以函数为例子,表示没有返回值(可以返回undefined、null)
function fn(): void{}

// never 表示永远不返回结果
function fn2(): void{
  throw new Error('报错了');
}

// 对象
let f: object;
// g 是一个对象,可以包含哪些属性。里面有个name属性,其值是字符串类型。age属性是可选的。
let g: {name: string, age?: number};
// [proName: string]: any 表示任意类型的属性
let h: {name: string, [propName: string]: any};
// 设置函数结构类型声明
let i: (a: number, b: number)=>number;
i = function(n1, n2): number{
  return n1 + n2;
}

// 字符串数组
let j: string[];
j = ['a', 'b']
let k: Array<number>; // 数字类型数组

// 元组 就是固定长度的数组
let l: [string, string];

// enum 枚举
enum Gender {
  Male,
  Female
}
let m: {name: string, gender: Gender}
m = {name:'sdf',gender:Gender.Male}

// & 同时
let n: {name: string} & {age: number}
n = {name: '小明', age: 18}

// 类型别名 简化类型使用
type myType = 1| 2| 3| 4;
let o: myType;

tsconfig.ts 文件配置选项

{
/*
 tsconfig.json 是ts编译器的配置文件,可以根据它的信息来对代码进行编译
*/

/*
 哪些ts文件需要被编译
 路径:
      ** 表示任意目录
      * 表示任意文件
*/
  "include": [
    "./**/*"
  ],

  // 不需要被编译的文件目录
  "exclude": [],

  // 定义被继承的配置文件 比如有xx.json,直接引入到这个tsconfig.js
  // "extends": "",

  // 指定被编译文件的列表,常用于文件少时
  // "files": [],

  // 编译器选项
  "compilerOptions": {
    // 用来指定ts被编译为es的版本 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'esnext'
    "target": "es6",

    // 指定要使用模块化的规范  'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'es2020', 'es2022', 'esnext', 'node12', 'nodenext'
    "module": "system",

    // 用来指定项目中要使用的库
    //'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2020.bigint', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref'
    // "lib": ["dom"],

    // 编译后文件所在的目录
    "outDir": "./dist",

    // 将代码合并成一个文件,所有全局作用域中的代码合并到同一个文件(一般通过打包工具,很少使用)
    // "outFile": "./dist/app.js",

    // 是否对js文件进行编译,默认false
    "allowJs": false,

    // 是否检查js代码是否符合语法规范
    "checkJs": false,

    // 是否移除注释
    "removeComments": false,

    // 不生成编译后的js文件
    "noEmit": false,
    
    // 当有错误时不生成编译后文件
    "noEmitOnError": false,

    // 所有严格检查的总开关
    "strict": false,

    // 是否启动严格模式
    "alwaysStrict": false,

    // 允许隐式any
    "noImplicitAny": false,
    
    // 允许不明确类型的this
    "noImplicitThis": false,

    // 不严格的检查空值
    "strictNullChecks": false,
  }
}

// 以abstract开头为抽象类,不能用来创建对象,专门用来被继承
abstract class Animal {
  // 实例只读属性
  readonly name: string = '小明';
  // 静态只读属性
  static readonly age: number = 18;
  weight:string;
  constructor(weight: string) {
    this.weight = weight;
  }
  sayHello() {
    console.log('say');
  }
  // 抽象方法,子类必须对抽象方法进行重写
  abstract say():void;
}
class Dog extends Animal {
  constructor(weight:string) {
    super(weight);
  }
  say() {
      console.log('aaaaaaa');
  }
}

// 接口用来定义一个类结构,用来定义一个类应该包含哪些属性和方法。
interface myInterface {
  name: string,
  age: number;
  sayHello():void
}
interface myInterface {
  gender: string,
}
const obj: myInterface = {
  name: 'aaa',
  age: 123,
  gender: '男',
  sayHello() {}
}
class MyClass implements myInterface {
  name: string;
  age: number;
  gender: string;
  constructor(name: string, age: number, gender: string) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
  sayHello() {}
}

// 属性封装
class A {
  // pubilc 默认的
  // private 私有属性,只能类内部进行访问(修改)。不被继承
  private _name: string;
  // protected 受包含的属性,只能在当前类和当前累的子类中使用。能被继承
  protected num: number;
  
  constructor(name: string, num: number) {
    this._name = name;
    this.num = num;
  }
  getName() {
    return this._name;
  }
}
class B {
  // 直接将属性定义在构造函数
  constructor(public name: string, private age: number){}
}

// 泛型 在定义函数或类时,如果遇到类型不明确的时候使用泛型。
function fn<T>(a: T): T{
  return a;
}
fn(10);// 不指定泛型,ts可以自动对类型进行推断
fn<string>('hello'); // 指定泛型
function fn2<T, K>(a: T, b: K):T{
  console.log(b);
  return a;
}
fn2(111,'hello');
fn2<number,string>(111,'12312');
interface Inter {
  length: number;
}
// T extends Inter 表示泛型T必须是Inter实现类(子类)
function fn3<T extends Inter>(a: T):number{
  return a.length;
}
fn3({length: 10});
class MyClass2<T> {
  name: T;
  constructor(name: T) {
    this.name = name;
  }
}
new MyClass2<string>('孙文斌');

使用webpack打包ts

>新开一个项目

初始化(生成package.json文件):

npm init

安装依赖:

npm i -D webpack webpack-cli typescript ts-loader

 生成html文件,并自动引入在内存中打包好的bundle.js文件

npm i -D html-webpack-plugin

一个小型的静态文件服务器。使用它,可以为webpack打包生成的资源文件提供Web服务

npm i -D webpack-dev-server

webpack打包后的dist目录中的所有文件将被删除一次

npm i -D clean-webpack-plugin

解决浏览器兼容性

npm i -D @babel/core @babel/preset-env babel-loader core-js

配置文件:webpack.config.js

// 引入一个包
const path = require('path');
// 引入html插件(生成对应的html文件)
const HTMLWebpackPlugin = require("html-webpack-plugin");
// 引入clean插件
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
// webpack 中的所有配置信息都应该写在module.exports中
module.exports = {
  // 指定入口文件
  entry:"./src/index.ts",
  //指定打包文件所在目录
  output:{
    //指定打包后的目录
    path: path.resolve(__dirname, 'dist'),
    // 打包后文件的文件
    filename: "bundle.js",
    // 告诉webpack不使用箭头函数
    environment:{
      arrowFunction:false
    }
  },
  // 指定webpack打包时要使用模块
  module:{
    // 指定要加载的规则
    rules: [
      {
        // 使用ts-loader去处理符合 /\.ts$/ 规则的文件
        // test指定的是规则生效的文件
        test: /\.ts$/,
        // 要使用的loader.(顺序从后往前执行)
        use: [
          // 配置babel
          {
            // 指定加载器
            loader: "babel-loader",
            // 设置babel
            options:{
              // 设置预定义的环境
              presets: [
                [
                  // 指定环境插件
                  "@babel/preset-env",
                  // 配置信息
                  {
                    targets: {
                      // 要兼容的目标浏览器
                      "chrome": "88",
                      "ie": "11",
                    },
                    // 下面两个参数意义:比如Promise,在ie里没有该方法,会从corejs引入自己版本实现的Promise功能。
                    // 指定corejs的版本
                    "corejs": "3",
                    // 使用corejs的方式 "usage"表示按需加载
                    "useBuiltIns": "usage"
                  }
                ]
              ]
            }
          },
          'ts-loader'
        ],
        // 要排除的文件
        exclude: /node-modules/
      }
    ],
     
  },
  // 配置webpack插件
  plugins: [
    new HTMLWebpackPlugin({
      // title: '这是一个自定义的title',
      template: "./src/index.html"
    }),
    new CleanWebpackPlugin()
  ],
  // 设置引用模块
  resolve: {
    // 凡是以ts、js的文件都可以用于模块(可以使用import、export)
    extensions: ['.ts','.js']
  },
  mode: 'production' // 设置mode
}

配置文件:tsconfig.json

{
  "compilerOptions": {
    "target": "ES2015",
    "module": "ES2015",
    "strict": true
  }
}

配置文件:package.json

添加一个build命令

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode production",
    "start": "webpack serve"
  },

例子(贪吃蛇小游戏)

项目地址:practice/snakeGame at main · txd688/practice · GitHub

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞天巨兽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值