TypeScript

TypeScript

  1. 安装typescript编译工具

    yarn add typescript
    
  2. 使用tsc来编译ts文件转为js文件

  3. 定义变量类型

    const a:number = 1 //数字类型
    const b:string = 'aaa' //字符串类型
    const c:null = nul //Null类型
    
    const d:void = undefined //Void类型
    function func():void{
    	console.log('无返回')
    }
    void类型变量只能赋值undefined和null
    
    const e:boolean = false//布尔类型
    
    //any可以为任意类型
    若不指定变量类型则自动变为any类型
    let any1:any = 1
    let any2:any = 'aaa'
    
    let list:number[] = [1,2,3]
    let list:Array<number> = [1,2,3]
    
    const obj:{foo:number,bar:string} = {foo:123,bar:"aaa"}//对象类型
    
  4. 元组类型

    //元组--明确元素个数和类型
    let x:[string,number] = ['hello',1]
    当元素越界后只要符合之前定义的元素类型
    x.[3] = 'aaa'//true
    x.[4] = ture //false
    
  5. 枚举类型

    //枚举--编号默认重0开始
    enum Color {Red,Green,Blue}
    let co:Color = Color.Green//co的值为1
    //枚举--修改编号从3开始
    enum Color {Red=3,Green,Blue}
    let co:Color = Color.Green//co的值为4
    //枚举--自定义值
    enum Color {Red:"red",Green:"green",Blue:"bule"}
    let co:Color = Color.Green//co的值为green
    
  6. 函数类型

    function func(a:number,b:string):string{
    	return 'func'
    }//string 为函数返回值类型
    func(1,'aaa')//传递的参数必须和定义类型和个数相同
    
  7. 类型断言–指定编译是类型的值

    const str:any = 'aaa'
    //下面两个写法作用相同
    const a = str as string
    const a = <string>str
    
  8. 报错信息设置为中文

    yarn tsc --locale zh-CN
    
  9. 接口

    interface Post{
    	title:string,
    	content:number,
    	subtitle?:string//可选成员,可以为string也可以为undefined
    	readonly suummary:string//添加readonly为只读成员
    }
    function printPost (post:Post){
    	console.log(post.title)
    	console.log(post.content)
    }
    printPost({
    	title:'文章',
    	content:111
    })
    
    interface Eat{
    	eat(food:string):void
    }
    interface Run{
    	run(m:string):void
    }
    类实现接口
    class P implements Eat,Run{
    	eat(food:string){
    		console.log(`${food}`)
    	}
    	run(m:string){
    		console.log(`${m}`)
    	}
    }
    
  10. 类–和es6中基本类似

    class Person{
    	private age:number //私有属性,只能在本类中使用
    	public name:string //默认就为public,都可以访问
    	protected gender:boolean //受保护的,只能在本类中和继承的类中使用
    	
    	static function add(){}//添加了static修饰符变为静态方法,不会被实例继承,只能通过类来调用
    }
    
  11. 抽象类–只能被继承不能被new

    abstract class Animal{
    	eat(food:string):void{
    		console.log("${food}")
    	}
    	abstract run (distance:number):void
    }
    
    class Dog extends Animal{
    	run(distance:number){
    		console.log("实现方法")
    	}
    }//继承抽象类会继承类中已经实现的方法,为实现的要自己编写来实现
    
  12. 泛型

    function identity<T>(arg: T): T {
        return arg;
    }
    
    let myIdentity: <T>(arg: T) => T = identity;
    //在使用是传递相同类型,可以支持任意类型
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值