标签:TypeScript const string Color number let 类型
TypeScript
-
安装typescript编译工具
yarn add typescript
-
使用tsc来编译ts文件转为js文件
-
定义变量类型
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"}//对象类型
-
元组类型
//元组--明确元素个数和类型 let x:[string,number] = ['hello',1] 当元素越界后只要符合之前定义的元素类型 x.[3] = 'aaa'//true x.[4] = ture //false
-
枚举类型
//枚举--编号默认重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
-
函数类型
function func(a:number,b:string):string{ return 'func' }//string 为函数返回值类型 func(1,'aaa')//传递的参数必须和定义类型和个数相同
-
类型断言–指定编译是类型的值
const str:any = 'aaa' //下面两个写法作用相同 const a = str as string const a = <string>str
-
报错信息设置为中文
yarn tsc --locale zh-CN
-
接口
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}`) } }
-
类–和es6中基本类似
class Person{ private age:number //私有属性,只能在本类中使用 public name:string //默认就为public,都可以访问 protected gender:boolean //受保护的,只能在本类中和继承的类中使用 static function add(){}//添加了static修饰符变为静态方法,不会被实例继承,只能通过类来调用 }
-
抽象类–只能被继承不能被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("实现方法") } }//继承抽象类会继承类中已经实现的方法,为实现的要自己编写来实现
-
泛型
function identity<T>(arg: T): T { return arg; } let myIdentity: <T>(arg: T) => T = identity; //在使用是传递相同类型,可以支持任意类型
标签:TypeScript,const,string,Color,number,let,类型 来源: https://blog.csdn.net/qq_47824967/article/details/122727170
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。