TypeScript入门
1. 变量的类型推断
let a= 'hello'
a= 1
2.数组的类型推断
const arr= [ '' , 1 , true ]
arr. push ( )
3.对象的类型推断
const user = { name : '' }
user. name
4.基础的变量声明
let a : number
let b : string
let c : boolean
let d : string[ ] | number[ ] | boolean[ ]
5.对象的类型声明
let a : object
let b : { name : string, age : number, url? : string}
6.组合类型的声明
let a : string| number
let b : ( string| number) [ ]
7.类型断言
let a : unknown= ''
let b : string= a
let c : string= a as string
let d : string= ''
let e : number= hd as unknown as number
8.void类型和never类型
function a ( ) : void {
}
function b ( ) : never{
}
9.函数类型以及参数声明
const func : function
func = ( ) => ''
function sum ( a : number,b: number, c : number= 0.6 ) : number{
return a+ b+ c
}
function add ( user : { name : string, age : number} ) : void {
console. log ( '添加用户' )
}
10.type对函数参数进行声明
type userType= { name : string, age : number}
let addUser ( user: userType) : void {
console. log ( '添加用户' )
}
11.函数的结构定义
type userTypeFun = ( user : { name : string, age : number} ) => number
let hd : ( user : { name : string, age : number} ) => number
hd : userTypeFun = ( user : { name : string, age : number} ) => {
return 1
}
hd ( { name : '' , age : 1 } )
12.剩余参数在TS中的使用
function sum ( ... args: number[ ] ) : number{
return args. reduce ( ( s, n ) => s+ n, 0 )
}
console. log ( sum ( 1 , 2 , 3 , 4 ) )
13.元组(位置类型对应)
let tuple : [ string, number, boolean] = [ '' , 1 , true ]
14.联合交叉类型
let obj: { name: string } & { age: string } | { name: number } & { age: string }
TypeScript的枚举和断言
1.Enum枚举类型
enum sexType{
A = 6 ,
B
}
console. log ( sexType. B )
2.as断言
function A ( arg : boolean) : string| number{
return arg? '' : 1
}
let B = A ( true ) as string
3.const断言(只读)
let a : string= 'A'
let b= 'C' as const
const arr= [ a, b, 1 , '' , true ] as const
const obj= { name : 1 } as const
4.解构中使用const断言
function hd ( ) {
let a= ''
let b= ( x: number, y : number) : number => x+ y4
return [ a, b] as [ typeof a, typeof b]
}
const [ a, b] = hd ( ) as [ string, Function]
console. log ( ( b as Function) ( 1 , 2 ) )
5.非空断言
const a : HTMLDivElement= document. querySelector ( '.hd' ) as HTMLDivElement
const a : HTMLDivElement= document. querySelector ( '.hd' ) !
6.DOM的类型推断和断言处理
const body : HTMLBodyElement= document. querySelector ( 'body' ) !
const div : Element= document. querySelector ( '.a' ) as HTMLDivElement
Element 普通元素
HTMLDivElement div元素
HTMLBodyElement body元素
HTMLLinkElement a元素
7.class构造函数的强制断言
class Hd {
el : HTMLDivElement
constructor ( el : HTMLDivElement) {
this . el= el
}
html ( ) {
return this . el. innerHTML
}
}
const el= document. querySelector ( '.a' ) as HTMLDivElement
new Hd ( el)
8.DOM事件的处理
const btn : HTMLButtonElement= document. querySelector ( '.btn' ) as HTMLButtonElement
btn. addEventListener ( 'click' , ( e : Event) => {
e. preventDefault ( )
const body= document. querySelector ( 'body' ) as HTMLBodyElement
body. insertAdjacentHTML ( 'beforeend' , '<h1></h1>' )
} )
TypeScript类与接口
1.TS来约束类
class User {
name : string
age : number
constructor ( n : string, a : number) {
this . name= n
this . age= a
}
info ( ) : string{
return ` ${ this . name} --- ${ this . age} `
}
}
const hd= new User ( 'qql' , 22 )
console. log ( hd. info ( ) )
2.public修饰符(外部,本类和子类使用)
class User {
public name : string
public age : number
constructor ( n : string, a : number) {
this . name= n
this . age= a
}
public info ( ) : string{
return ` ${ this . name} --- ${ this . age} `
}
}
const hd= new User ( 'qql' , 22 )
console. log ( hd. info ( ) )
3.protected修饰符(本类和子类使用)
class User {
protected name : string
protected age : number
constructor ( n : string, a : number) {
this . name= n
this . age= a
}
protected info ( ) : string{
return ` ${ this . name} --- ${ this . age} `
}
}
const hd= new User ( 'qql' , 22 )
class U extends User {
constructor ( n : string, a : number) {
super ( n, a)
this . name= n,
this . age= a
}
}
4.private修饰符(本类使用)
class User {
private name : string
private age : number
constructor ( n : string, a : number) {
this . name= n
this . age= a
}
private info ( ) : string{
return ` ${ this . name} --- ${ this . age} `
}
}
class U extends User {
constructor ( n : string, a : number) {
super ( n, a)
}
}
const hd= new User ( 'qql' , 22 )
5.类中重写继承父类方法
class User {
name : string
age : number
constructor ( n : string, a : number) {
this . name= n
this . age= a
}
protected info ( ) : string{
return ` ${ this . name} --- ${ this . age} `
}
protected info2 ( ) : string{
return ` ${ this . name} --- ${ this . age} `
}
private info3 ( ) : string{
return ` ${ this . name} --- ${ this . age} `
}
}
class U extends User {
constructor ( n : string, a : number) {
super ( n, a)
}
protected info ( ) : string {
return ` ${ this . name} --- ${ this . age} `
}
public info2 ( ) : string {
return ` ${ this . name} --- ${ this . age} `
}
}
6.readonly修饰符
class Axios {
public readonly site: string= ''
public constructor ( site : string) {
this . site= site
}
}
const b= new Axios ( '' )
b. site= ''
7.类构造方法constructor
class User {
constructor ( public name : string) {
}
}
8.static静态属性语句
class User {
static site : string= ''
}
const instance = new User ( )
instance. site
console. log ( User. site)
9.Typescript实现单例模式
class Axios {
private static instance : Axios | null = null
private constructor ( ) {
console. log ( '构造方法' )
}
static make ( ) : Axios{
if ( Axios. instance=== null ) {
console. log ( '创建axios' )
Axios. instance= new Axios ( )
}
return Axios. instance
}
}
const instance= Axios. make ( )
10.访问器get和set
class User {
private _name : string
constructor ( name : string) {
this . _name= name
}
public get name ( ) : string{
return this . _name
}
public set name ( name : string) {
this . _name= name
}
}
const A = new User ( 'qql' )
A . name= 'qq'
console. log ( A . name)
11.Typescript抽象类
abstract class Animation {
abstract name: string
abstract move ( ) : void
protected getPos ( ) : number[ ] {
return [ 100 , 300 ]
}
}
class Tank extends Animation {
name : '敌方坦克'
public move ( ) : void {
console. log ( '敌方坦克移动' )
}
}
12.类实现interface接口
interface Animati {
end ( ) : void
}
interface Animatio {
name : string
move ( ) : void
}
class Tank implements Animatio , Animati{
name : '敌方坦克'
public move ( ) : void {
console. log ( '敌方坦克移动' )
}
public end ( ) : void {
console. log ( '游戏结束' )
}
}
13.interface接口对对象的约束
interface Userinterface {
name : string
age : number
weight? : number
info ( ) : string
[ key: string] : any
}
let hd : Userinterface= {
name : 'qql' ,
age : 18 ,
info ( ) {
return ` ${ this . name} - ${ this . age} `
}
}
14.interface接口对参数的约束
type userType= { name : string, age : number}
interface userinterface {
name : string
age : number
}
function isLock ( user : userType) : userType{
return { name : 'qql' , age : 19 }
}
class ISlock {
public info : userinterface
constructor ( info : userinterface) {
this . info= info
}
}
15.interface接口对数组的约束
interface userinterface {
name : string
age : number
}
const hd : userinterface= {
name : 'qql' ,
age : 18
}
const users : userinterface[ ] = [ hd]
16.interface接口案例
interface PayInterface {
handle ( price: number) : void
}
class AliPay implements PayInterface {
public handle ( price: number) : void {
console. log ( '支付宝付款' , price)
}
}
class Wepay implements PayInterface {
public handle ( price: number) : void {
console. log ( '微信付款' , price)
}
}
function pay ( type : string, price : number) {
let pay : PayInterface
switch ( type) {
case 'alipay' :
pay= new AliPay ( )
break
case 'wepay' :
pay= new Wepay ( )
}
pay. handle ( price)
}
pay ( 'alipay' , 100 )
17.interface声明函数
interface Pay {
( private : number) : boolean
}
const we : Pay = ( price : number) => true
18.interface接口的合并
interface A {
name : string
}
interface B extends A {
age : number
}
interface C {
name : string
}
interface C {
age : number
}
19.type和interface差异
type IsAdmin= boolean
type name= {
name : string
}
type age= {
age : string
}
type User= age& name
type name= {
name : string
}
type age= {
age : string
}
type User= age& name
class person implements User {
name : ""
age : ''
}
20.ts中更新全局接口interface
interface Window {
myname : string
}
export { }
function Person ( this : Window, name : string) {
this . myname= name
}
TypeScript泛型
1.什么是泛型
function a ( a : string) : string{
return a
}
function b ( b : boolean) : boolean{
return b
}
let a1= a ( '' )
let b1= b ( true )
function c< T > ( c: T ) : T {
return c
}
let c1= c< string> ( '' )
let c2= c< boolean> ( true )
2.泛型的继承
function getLength< T extends { length : number} > ( l: T ) : number{
return l. length
}
function getLength< T > ( l: T [ ] ) : number{
return l. length
}
3.泛型在类中的使用
class A < T > {
data : T [ ] = [ ]
push ( ... items: T [ ] ) {
this . data. push ( ... items)
}
length ( ) : number{
return this . data. length
}
}
const B = new A < number> ( )
B . push ( 1 , 2 , 3 )
console. log ( B . length ( ) )
4.构造函数中使用泛型
class User < T > {
public constructor ( private _user : T ) { }
public user ( ) : T {
return this . _user
}
}
interface Userinterface {
name : string,
age : number
}
const obj= new User < Userinterface> ( { name : 'A' , age : 12 } )
console. log ( obj. user ( ) )
5.接口使用泛型
interface Articleinterface < T , C > {
title : string
isLock : T
comments : C [ ]
}
type commentType= {
content : string
}
const hd : Articleinterface< boolean, commentType>= {
title : '' ,
isLock : true ,
comments : [ { content : '' } ]
}
TypeScript装饰器
1.打开ts的装饰器配置项
tsc -- init
配置文件中搜索decora
打开 "experimentalDecorators" : true ,
"emitDecoratorMetadata" : true ,
2.类装饰器
const moveDecorator : ClassDecorator = ( target : Function) => {
target. prototype. getPosition= ( ) : { x : number, y : number} => {
return { x : 100 , y : 100 }
}
}
@moveDecorator
class Tank { }
const t= new Tank ( )
console. log ( ( t as any) . getPosition ( ) )
3.类装饰器的叠加
const moveDecorator : ClassDecorator = ( target : Function) => {
target. prototype. getPosition= ( ) : { x : number, y : number} => {
return { x : 100 , y : 100 }
}
}
const musicDecorator : ClassDecorator = ( target : Function) => {
target. prototype. playMusic= ( ) : void => {
console. log ( '播放音乐' )
}
}
@musicDecorator
@moveDecorator
class Tank { }
const t= new Tank ( )
console. log ( ( t as any) . getPosition ( ) , ( t as any) . playMusic ( ) )
4.类装饰器完成消息响应
const MessageDecorator : ClassDecorator = ( target : Function) => {
target. prototype. message = ( content : string) => {
console. log ( content)
}
}
@MessageDecorator
class LoginController {
public login ( ) {
console. log ( '登录业务' )
this . message ( '恭喜登录成功' )
}
}
new LoginController ( ) . login ( )
5.类装饰器工厂
const MessageDecoratorFactory= ( name: string) : ClassDecorator => {
return ( target : Function) => {
target. prototype. message = ( content : string) => {
console. log ( name+ content)
}
}
}
@MessageDecoratorFactory ( 'qql' )
class LoginController {
public login ( ) {
console. log ( '登录业务' )
this . message ( '恭喜登录成功' )
}
}
new LoginController ( ) . login ( )
6.方法装饰器
const showDecorator : MethodDecorator = ( target : Object, propertyKey : string | symbol, descriptor : PropertyDescriptor) => {
descriptor. value = ( ) => {
console. log ( 'a' )
}
}
class User {
@showDecorator
public show ( ) {
console. log ( 1 )
}
}
User. show ( )
7.方法装饰器阻止函数第二次声明(静态函数)
const showDecorator : MethodDecorator = ( target : Object, propertyKey : string | symbol, descriptor : PropertyDescriptor) => {
descriptor. writable= false
}
class User {
@showDecorator
public static show ( ) {
console. log ( 1 )
}
}
User. show ( )
8.使用方法装饰器给一段文字添加背景
const highlightDecorator : MethodDecorator = ( target : Object, propertyKey : string | symbol, descriptor : PropertyDescriptor) => {
const method= descriptor. value
descriptor. value = ( ) => {
return ` <h1 style="background:black;color:white"> ${ method ( ) } </h1> `
}
}
class User {
@highlightDecorator
public static show ( ) {
return 'aaaaaa'
}
}
console. log ( User. show ( ) )
9.方法延迟装饰器
const SleepDecorator : MethodDecorator = ( target : Object, propertyKey : string | symbol, descriptor : PropertyDescriptor) => {
const method= descriptor. value
descriptor. value = ( ) => {
setTimeout ( ( ) => {
method ( )
} , 2000 )
}
}
class User {
@SleepDecorator
public static show ( ) {
console. log ( '10' )
}
}
User. show ( )
10.方法装饰器工厂实现延迟
const SleepDecoratorFactory = ( times : number) => {
return ( target : Object, propertyKey : string | symbol, descriptor : PropertyDescriptor) => {
const method= descriptor. value
descriptor. value = ( ) => {
setTimeout ( ( ) => {
method ( )
} , times)
}
}
}
class User {
@SleepDecoratorFactory ( 2000 )
public static show ( ) {
console. log ( '10' )
}
}
User. show ( )
11.方法装饰器进行异常处理
const ErrorDecortator = ( target : Object, propertyKey : string | symbol, descriptor : PropertyDescriptor) => {
const method= descriptor. value
descriptor. value = ( ) => {
try {
method ( )
} catch ( e) {
console. log ( '错' )
}
}
}
class User {
@ErrorDecortator
public show ( ) {
throw new Error ( '出错了' )
}
}
new User ( ) . show ( )
12.方法装饰器工厂对异常输出信息定制
const ErrorDecortatorFactory= ( title: string= '出错了' ) => {
return ( target : Object, propertyKey : string | symbol, descriptor : PropertyDescriptor) => {
const method= descriptor. value
descriptor. value = ( ) => {
try {
method ( )
} catch ( e) {
console. log ( title)
}
}
}
}
class User {
@ErrorDecortatorFactory ( )
public static show ( ) {
throw new Error ( '出错了' )
}
}
User. show ( )
13.方法装饰器完成权限管理
type userType= {
name : string
isLogin : boolean
Authority : string[ ]
}
const user : userType= {
name : 'admin' ,
isLogin : true ,
Authority : [ 'store' ]
}
const AccesssDecortorFactory= ( keys: string[ ] ) : MethodDecorator => {
return ( target : Object, propertyKey : string | symbol, descriptor : PropertyDescriptor) => {
const method= descriptor. value
const validate = ( ) => keys. every ( k => {
return user. Authority. includes ( k)
} )
descriptor. value = ( ) => {
if ( user. isLogin=== true && validate ( ) ) {
return method ( )
}
console. log ( '请登录' )
}
}
}
class Article {
show ( ) {
console. log ( '显示文章' )
}
@AccesssDecortorFactory ( [ 'store' , '1' ] )
store ( ) {
console. log ( '保存文章' )
}
}
new Article ( ) . show ( )
new Article ( ) . store ( )
14.方法装饰器模拟发送请求
const RequestDecorator= ( url: string) : MethodDecorator => {
return ( target : Object, propertyKey : string | symbol, descriptor : PropertyDescriptor) => {
const method= descriptor. value
new Promise ( resolve => {
setTimeout ( ( ) => {
resolve ( { name : "qql" , age : 18 } )
} , 2000 )
} ) . then ( user => {
method ( user)
} )
}
}
class User {
@RequestDecorator ( 'http:xx/xx/api' )
all ( users : any[ ] ) {
console. log ( users)
}
}
15.属性装饰器
const PropDecorator : PropertyDecorator = ( target : Object, propertyKey : string | symbol) => {
}
class A {
@PropDecorator
public title : string | undefined = '1'
}
16.属性装饰器实现大小写转换
const lowerDecorator : PropertyDecorator = ( target : Object, propertyKey : string | symbol) => {
let value : string
Object. defineProperty ( target, propertyKey, {
get : ( ) => {
console. log ( '我被读取了' )
return value. toLocaleLowerCase ( )
} ,
set : v => {
value= v
}
} )
}
class A {
@lowerDecorator
public title : string| undefined
}
new A ( ) . title= 'ASDASDAS'
console. log ( new A ( ) . title)
17.属性装饰器实现随机颜色
const RandomDecotor : PropertyDecorator = ( target : Object, propertyKey : string | symbol) => {
const colors : string[ ] = [ 'red' , 'black' , 'yellow' ]
Object. defineProperty ( target, propertyKey, {
get ( ) {
return colors[ Math. floor ( Math. floor ( Math. random ( ) * colors. length) ) ]
}
} )
}
class A {
@RandomDecotor
color : string| undefined
public draw ( ) {
console. log ( this . color)
}
}
new A ( ) . draw ( )
18.参数装饰器
const ParameDecorator : ParameterDecorator = ( target : Object, propertyKey : string | symbol, parameterIndex : number) => {
console. log ( args)
}
class A {
show ( id : number= 1 , @ParameDecorator content: string) { }
}
19.参数装饰器的元数据的简单使用
import 'reflect-metadata'
let A = {
name : 'qql'
}
Reflect. defineMetadata ( 'qq' , { url : 'http:xxxx/xxx' } , A , 'name' )
console. log ( Reflect. getMetadata ( 'qq' , A , 'name' ) )
20.参数的简单验证
import 'reflect-metadata'
let requiredParams : number[ ] = [ ]
const RequiredDecorator : ParameterDecorator = ( target : Object, propertyKey : string | symbol, parameterIndex : number) => {
requiredParams. push ( parameterIndex)
Reflect. defineMetadata ( 'required' , requiredParams, target, propertyKey)
}
const valDecorator : MethodDecorator = ( target : Object, propertyKey : string | symbol, descriptor : PropertyDescriptor) => {
const method= descriptor. value
descriptor. value = function ( ) {
const Params : number[ ] = Reflect. getMetadata ( 'required' , target, propertyKey)
Params. forEach ( keys => {
if ( Params. length> arguments. length|| arguments[ keys] === undefined ) {
throw new Error ( '参数不够' )
}
} )
return method . apply ( this , arguments)
}
}
class User {
@valDecorator
find ( @RequiredDecorator name: string, @RequiredDecorator id: number ) { }
}
new User ( ) . find ( 'qql' , 1 )
TypeScript
1.ts中使用Promise
interface ResItf {
code : number
data : { a : number, b : number} [ ]
message : string
}
let p : Promise< ResItf>= new Promise ( ( resolve, reject ) => {
resolve ( {
code : 0 ,
data : [ { a : 1 , b : 2 } , { a : 11 , b : 22 } ] ,
message : ''
} )
} )
p. then ( res => {
if ( res. code=== 0 ) {
res. data. map ( item => item. a)
}
} )
2.ts函数中的this
export { }
type objType= {
A : string,
B : ( m : string) => void
}
let obj : objType= {
A : '' ,
B : ( ) => { }
}
function B < T extends objType > ( this : T , C : string) {
this . A = C
}
obj. B = B < objType>
3.ts的工具类型Partial
interface A {
name : string
age : number
}
let obj : Partial< A >= {
name : ''
}
4.ts工具类型Required
export { }
interface A {
name? : string
age? : number
}
let obj : Required< A >= {
name : '' ,
age : 1
}
5.ts中的keyof和in
export { }
interface A {
name : string
age : number
[ idx: number] : number
}
type a= keyof A
let p : a
p= 'name'
p= 'age'
p= 1
type StrOrNum= string| number
type PItf= {
[ k in StrOrNum] : string
}
let obj : PItf= {
a : '' ,
10 : ''
}