typescript

编译

  • -w

Watch

tsc app.ts -w

ts.config.json

编译配置文件

  • Tsc -w

监听所有文件

  • include
"include": ["./01*.ts"]
  • files

指定需要编译的文件

  • exclude
compileOptions

编译器选项

  1. target 编译后的es版本

默认es3

target: 'ES3';
es3 es6 es2015 es2016 es2017 es2018 es2019 es2020 esnext
  1. module 使用模块化规范
module: 'es2015' // es6的模块化规范

'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'es2020', 'es2022', 'esnext', 'node12', 'nodenext'.

Es6 == es2015

  1. lib 要使用的依赖库

一般不需要修改,当运行环境不是浏览器时,需要修改

// 默认值

  1. outDir 编译后文件路径
outDir: './dist'
  1. outFile 将代码合并成一个文件

  2. allowJs 允许使用js文件

  3. checkJs 是否检查js代码语法

  4. removeComments 删除注释

  5. noEmit 不生产编译后的文件

  6. noEmitOnError 当有错误时,不生成编译后文件

  7. alwaysStrict 设置编译后文件是否使用严格模式 false

  8. noImplicitAny 是否允许设置隐式any类型

  9. noImplicitThis 不允许隐式this

  10. strictNullChecks 空置检查

  11. strict 所有严格检查的总开关

webpack打包

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

ts-loader

const path = require('path')

module.exports = {
  entry: "./src/index.ts",
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'index.js',
  },
  // 打包中使用的模块
  module: {
    rules: [
      {
        test: /\.ts&/,
        use: 'ts-loader',
        exclude: /node_modules/,
      }
    ],
  },
}

  • 打包命令
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },

html-webpack-plugin

自动生成html文件,并且自动引入script标签、style标签等资源文件

webpack-dev-server

webpack开发服务器

"scripts": {
    "serve": "webpack serve --open",
    "build": "webpack"
  },

clean-webpack-plugin

打包前自动删除上次打包文件

  • resolve
// 识别模块

resolve: {
  extensions: ['*.ts', '*.js'],
},

联合类型、交叉类型、类型断言

  • 联合类型
let n : number | string;
  • 交叉类型
interface Map {
  name: string;
}
interface User {
  age: number;
}
let m: User & Map = {
  name: 'aaa',
  age: 100,
}

必须满足两种类型,的所有属性

  • 类型断言
let n : number = 100;
let m : string = (n as string);

tsc index.ts --watch


let body: HTMLElement = document.body;
let allDiv: NodeList = document.querySelectorAll('div');
//读取div 这种需要类型断言 或者加个判断应为读不到返回null
let div:HTMLElement = document.querySelector('div') as HTMLDivElement
document.addEventListener('click', function (e: MouseEvent) {



interface HTMLElementTagNameMap {
    "a": HTMLAnchorElement;
    "abbr": HTMLElement;
    "address": HTMLElement;
    "applet": HTMLAppletElement;
    "area": HTMLAreaElement;
    "article": HTMLElement;
    "aside": HTMLElement;
    "audio": HTMLAudioElement;
    "b": HTMLElement;
    "base": HTMLBaseElement;
    "bdi": HTMLElement;
    "bdo": HTMLElement;
    "blockquote": HTMLQuoteElement;
    "body": HTMLBodyElement;
    "br": HTMLBRElement;
    "button": HTMLButtonElement;
    "canvas": HTMLCanvasElement;
    "caption": HTMLTableCaptionElement;
    "cite": HTMLElement;
    "code": HTMLElement;
    "col": HTMLTableColElement;
    "colgroup": HTMLTableColElement;
    "data": HTMLDataElement;
    "datalist": HTMLDataListElement;
    "dd": HTMLElement;
    "del": HTMLModElement;
    "details": HTMLDetailsElement;
    "dfn": HTMLElement;
    "dialog": HTMLDialogElement;
    "dir": HTMLDirectoryElement;
    "div": HTMLDivElement;
    "dl": HTMLDListElement;
    "dt": HTMLElement;
    "em": HTMLElement;
    "embed": HTMLEmbedElement;
    "fieldset": HTMLFieldSetElement;
    "figcaption": HTMLElement;
    "figure": HTMLElement;
    "font": HTMLFontElement;
    "footer": HTMLElement;
    "form": HTMLFormElement;
    "frame": HTMLFrameElement;
    "frameset": HTMLFrameSetElement;
    "h1": HTMLHeadingElement;
    "h2": HTMLHeadingElement;
    "h3": HTMLHeadingElement;
    "h4": HTMLHeadingElement;
    "h5": HTMLHeadingElement;
    "h6": HTMLHeadingElement;
    "head": HTMLHeadElement;
    "header": HTMLElement;
    "hgroup": HTMLElement;
    "hr": HTMLHRElement;
    "html": HTMLHtmlElement;
    "i": HTMLElement;
    "iframe": HTMLIFrameElement;
    "img": HTMLImageElement;
    "input": HTMLInputElement;
    "ins": HTMLModElement;
    "kbd": HTMLElement;
    "label": HTMLLabelElement;
    "legend": HTMLLegendElement;
    "li": HTMLLIElement;
    "link": HTMLLinkElement;
    "main": HTMLElement;
    "map": HTMLMapElement;
    "mark": HTMLElement;
    "marquee": HTMLMarqueeElement;
    "menu": HTMLMenuElement;
    "meta": HTMLMetaElement;
    "meter": HTMLMeterElement;
    "nav": HTMLElement;
    "noscript": HTMLElement;
    "object": HTMLObjectElement;
    "ol": HTMLOListElement;
    "optgroup": HTMLOptGroupElement;
    "option": HTMLOptionElement;
    "output": HTMLOutputElement;
    "p": HTMLParagraphElement;
    "param": HTMLParamElement;
    "picture": HTMLPictureElement;
    "pre": HTMLPreElement;
    "progress": HTMLProgressElement;
    "q": HTMLQuoteElement;
    "rp": HTMLElement;
    "rt": HTMLElement;
    "ruby": HTMLElement;
    "s": HTMLElement;
    "samp": HTMLElement;
    "script": HTMLScriptElement;
    "section": HTMLElement;
    "select": HTMLSelectElement;
    "slot": HTMLSlotElement;
    "small": HTMLElement;
    "source": HTMLSourceElement;
    "span": HTMLSpanElement;
    "strong": HTMLElement;
    "style": HTMLStyleElement;
    "sub": HTMLElement;
    "summary": HTMLElement;
    "sup": HTMLElement;
    "table": HTMLTableElement;
    "tbody": HTMLTableSectionElement;
    "td": HTMLTableDataCellElement;
    "template": HTMLTemplateElement;
    "textarea": HTMLTextAreaElement;
    "tfoot": HTMLTableSectionElement;
    "th": HTMLTableHeaderCellElement;
    "thead": HTMLTableSectionElement;
    "time": HTMLTimeElement;
    "title": HTMLTitleElement;
    "tr": HTMLTableRowElement;
    "track": HTMLTrackElement;
    "u": HTMLElement;
    "ul": HTMLUListElement;
    "var": HTMLElement;
    "video": HTMLVideoElement;
    "wbr": HTMLElement;
}


  • promise
new Promise<string>(resolve => {
  resolve('hello');
}).then(msg => {
  console.log(msg)
})

类型别名

type s = string;

type cb = () => string;

type t = 'on' | 'off'

never


interface A {
  type: '1'
}
interface B {
  type: '2'
}

type All = A | B

function fun(val: All) {
  switch (val.type) {
    case '1':
      break;
    case '2':
      break
    default:
      let check:never = val;
      break
  }
}

symbol

let a: symbol = Symbol(1)
let b: symbol = Symbol(1)
console.log(a == b);  // false
  • key
let name:symbol = Symbol('abc')
let obj = {
  [name]: 'admin',
  age: 100
}
for (let k in obj) {
  console.log(k) // age
}
console.log(Object.keys(obj)) // ['age']
console.log(Object.getOwnPropertyNames(obj))  // ['age']
  • to json
console.log(JSON.stringify(obj))  // {age: 100}
  • 获取symbol值
console.log(Object.getOwnPropertySymbols(obj))  // Symbol(abc)
console.log(Reflect.ownKeys(obj)) //['age', Symbol(abc)]
  • symbol迭代器
let arr: number[] = [1,2,3]
let iterator: Iterator<number> = arr[Symbol.iterator]()
console.log(iterator.next()) // {value: 1, done: false}
let arr: number[] = [1,2,3]
let iterator: Iterator<number> = arr[Symbol.iterator]()
let val: any = {done: false}
while (!val.done) {
  console.log(val = iterator.next())
}
  • set 迭代器
let set: Map<any, any> = new Map();
set.set(1, 20);
for (let item of set) {
  console.log(item)
}

let set: Set<any> = new Set<any>([1, 2, 3]);
for (let item of set) {
  console.log(item)
}

泛型

function add<T>(a: T, b: T): T[] {
  return [a, b];
}

add(1,2)
add('a', 'b')
  • 泛型约束

interface Len {
  length: number;
}
function add<T extends Len>(a: T, b: T): T[] {
  return [a, b];
}

add('a', 'b')
  • keyof
function add<T, K extends keyof T>(obj: T, key: K): any {
  return obj[key];
}

let obj = {
  a: 1,
  b: 2,
  c: 3
}
add(obj,  'b')
posted @ 2022-07-08 08:06  fight139  阅读(28)  评论(0编辑  收藏  举报