TypeScript

npm init -y 初始化package.json文件

//webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const path=require('path');
module.exports={
  entry:"./src/index.ts",
  output:{
    filename:"main.js"
    
  },
  resolve:{
    extensions:['.ts','.js','.tsx']
  },
  module:{
    rules:[{
      test:/\.tsx?$/,
      use:'ts-loader',
      exclude:/node_modules/
    }]
  },
  devtool: process.env.NODE_ENV === 'production' ? false : 'inline-source-map',
  devServer:{
    static: {
      directory: path.join(__dirname, 'dist'),
    },
    compress: true,
    host:'localhost',
    port:8089
  },
  plugins:[
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns:['./dist']
    }),
    new HtmlWebpackPlugin({
      template:'./src/template/index.html'
    })
  ]
}

//package.json
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "cross-env NODE_ENV=development webpack-dev-server --config ./build/webpack.config.js",
    "build": "cross-env NODE_ENV=production webpack --config ./build/webpack.config.js"
  },

基础类型
布尔:
// let bool:boolean=false
let bool:boolean
bool=tru

// 数值类型
let num:number=123
num=0b11101 //二进制
num=0o173 //八进制
num=0x7b //十六进

// 字符串类型
let str:string
str=‘abc’
str=数值是${num}
console.log(str)

// 数组类型
// [1,2,3]
// 写法1
let arr:number[]
arr=[5]
// 写法二
let arr1:Array
let arr3:(string|number)[]
arr3=[1,‘a’]

// 元组类型 一一对应,也不可以超长
let tuple:[string,number,boolean]
tuple=[‘a’,1,false]

// 枚举类型,根据名字取得索引值
enum Roles{
SUPER_ADMIN =1, //Roles[Roles[“SUPER_ADMIN”]=0]=“SUPERADMIN”
ADMIN,
USER
}

// any类型
let value:any
value=‘abc’
value=123
value=false
const arr4:any[]=[1,‘a’]

// void类型 指定返回值viod('strict为false时,void可以赋给undefined和null)而不是undefined
const consoleText=(text:string):void=>{
console.log(text)
}

// never类型 从不存在的类型 抛错 死循环
const errorFunc=(message:string):never=>{
throw new Error(message)
}
const infiniteFunc=():never=>{
while(true){}
}

// object类型 赋值是赋地址
function getObject(obj:object):void{
console.log(obj)
}
getObject(obj2)

// 类型断言,表明知道是string类型
const getLength = (target:string|number):number => {
if((target).length||(target as string).length===0){
return (target).length
}else{
return target.toString().length
}
}

Symbol
// symbol是独一无二的值
const s = Symbol(123) //ts下只能传入string或者number
console.log(Boolean(s))
const s5=Symbol(‘name’)
const info2={
[s5]:‘lison’
}
console.log(info2[s5])
// for in 、Object.keys(),Object.getOwnPropertyNames(info),JSON.stringify都不可以获取symbol属性
console.log(Object.getOwnPropertySymbols(info2))
console.log(Reflect.ownKeys(info2))

//Symbol.for() Symbol.keyFor()
const s8=Symbol.for(‘lison’)
const s9=Symbol.for(‘lison’)
// s8=s9
Symbol.keyFor(s8)
// 拿到用symbol.for定义的值

isConcatSpreadable是否扁平化
let arrs=[1,2]
console.log([].concat(arrs,[3,4])) //[1,2,3,4]
arrs[Symbol.isConcatSpreadable]=false
console.log([].concat(arrs,[3,4])) //[[1,2],3,4]

Symbol.species把衍生对象(map return 的之类) instanceof (构造函数)设置为false

Symbol.match/Symbol.split/Symbol.search/Symbol.iterator

接口

// 接口 类型 或存在? 多余属性as
interface NameInfo{
  firstName:string,
  lastName:string
}
const getFullName=({firstName,lastName}:NameInfo):string=>{
  return `${firstName} ${lastName}`
}
getFullName({
  firstName:'haha',
  lastName:'li'
})
interface Vegetable{
  color?:string,   //可以没有
  readonly type:string   //只读
  [prop:string]:any
}
const getVegetables=({color,type}:Vegetable)=>{
  return `A ${color?(color+''):''}${type}`
}
getVegetables({
  type:'tomato',
})

interface ArrInter{
  0:number,
  readonly 1:string
}
let arr7:ArrInter=[1,'a']

type AddFunc=(num1:number,num2:number) =>number
const add:AddFunc=(n1,n2)=>n1+n2

interface RoleDic{
  [id:string]:string
}
const role1:RoleDic={
  'a':'super_admin',
   1:'admin',
}

// 接口继承
interface Vegetables{
  color:string
}
interface Tomato extends Vegetables{
  radius:number
}
interface Carrot extends Vegetables{
  length:number
}
const tomato:Tomato={
  radius:1,
  color:'red'
}
const carrot :Carrot={
  length:2,
  color:'orange',
}

interface Counter{
  ():void,
  count:number
}
const getCounter=():Counter=>{
  const c=()=>{c.count++}
  c.count=0
  return c
}
const counter:Counter=getCounter()
counter()

slice.apply[]伪转真,slice取length前面的值

函数

// 函数类型
let add1:(x:number,y:number)=>number
add1 = (arg1:number,arg2:number):number=>arg1+arg2

type Add=(x:number,y:number)=>number
let addFunc:Add
addFunc=(arg1:number,arg2:number)=>arg1+arg2

// arg3可有可没有
type AddFunction=(arg1:number,arg2:number,arg3?:number)=>number
// const handleData=(arg1:number,...args:number[])=>{

// }

// 函数重载
function handleData(x:string):string[]
function handleData(x:number):number[]
function handleData(x:any):any{
  if(typeof x ==='string'){
    return x.split('')
  }else{
    return x.toString().split('').map((item: any)=>Number(item))
  }
}

泛型

// T表明泛型(用大写字母),可以应用的时候再传入类型
// 1
const getArray = <T>(value:T,times:number=5):T[]=>{
  return new Array(times).fill(value)
}
getArray<number>(123,4).map((item)=>item.toFixed)
// 2
const getArray1=<T,U>(value:T ,value1:U,times:number=5):Array<T,U>[]=>{
  return new Array(times).fill([value,value1])
}
getArray1<number,string>(1,'a',3).forEach((item)=>{
  console.log(item[0])
})
// 3
type GetArrayS=<T>(arg:T,times:number)=>T[]
let getArrays:GetArrayS=(arg:any,time:number)=>{
  return new Array(time).fill(arg)
}
// 4,约束一定要有长度
interface valueWithLength{
  length:number
}
const getArray7=<T extends valueWithLength>(arg:T ,times):T[]=>{
  return new Array(times).fill(arg)
}
getArray([1,2],3)
getArray('123',3)
getArray({
  length:2
})
// 5
const getProps=<T ,K extends keyof T>(object:T,propName:K)=>{
  return object[propName]
}
const objs={
  a:'a',
  b:'b'
}
getProps(objs,'a')
// getProps(objs,'c')对象上没有,会报错

// private私有的
class Parent{
  private age:number
  constructor(age:number){
   
}
// pubilc
// protected受保护的  能访问方法,不能访问属性 在构造前加protected,不能直接用父类创造对象
// 只能通过继承父类,再用子类创建
public readonly name:string //只能读
public static age
public static getName(){}//只能通过父类来访问
constuctor(name:string,age?:number,public sex?:string){} //可选参数

// 抽象类一般被用来继承而不创建实例
abstract class People{
  constructor(public name:string){}
  public abstract printname():void
}
class Man extends People{
  constructor(name:string){
    super(name)
    this.name=name
  }
  public printName(){
    console.log(this.name)
  }
}
const m=new Man('lison')
m.printName()

abstract class People{
  public abstract _name:string
  abstract get insideName():string
  abstract set insideName(value:string)
}
class P extends People{
  public _name:string
  public insideName:string
}


class People{
  constructor(public name:string{})
}
let p2:People=new People('lison')
class Animal{
  constructor(public name :string){}
}
p2=new Animal('haha')

//类实现接口
interface FoodInterface{
  type:string
}
class FoodClass implements FoodInterface{
  public type:string
}

//接口继承类
class A{
  protected name:string
}
interface I extends A{}
class B implements I{
  public name:string
}

// 泛型
const creat=<T>(c:new()=>T):T=>{
  return new c()
}
class Infos{
  public age:number
  constructor(){
    this.age=18
  }
}
create <Infos>(Infos).age 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值