1. 在桌面打开命令窗口
  2. npm i typescript -g
  3. npm i ts-node -g
  4. tsc --version

ts编译成js

  1. 1. tsc hello.ts
  2. 2. ts-node hello.ts
  3. 3. Code-Runner //如果有乱码,

2.ts中的数据类型

  1. var s:string = "hello world";
  2. var n:number = 10;
  3. var a:string[]=["hello","world"]
  4. var b:boolean = true
  5. var arr:Array<number> = [1,2,3]
  6. var obj:object = {name:"cheng",age:13}
  7. var list:Array<object> = [{name:"cheng",age:14}]
  8. console.log(s);

2-2 元组

  1. 给数组的每个元素指定一个类型
  2. var s:[string,number] = ["hello",1];
  3. console.log(s);

2-3 enum 枚举类型

  1. 定义一个特定类型的集合
  2. enum Status {
  3. success=200,
  4. error=404,
  5. serverError=500
  6. }
  7. var success:Status = Status.success;
  8. console.log(success)

2-4 null-undefined

  1. var num = null;
  2. num =10 //报错

3.声明函数

  1. //声明一个有返回值的函数
  2. function go():string{
  3. return "hello"
  4. }
  5. //没有返回值的函数
  6. function show():void{
  7. console.log("hello")
  8. }

4.函数的传参

  1. function fun(s:string):string{
  2. console.log(s);
  3. return s;
  4. }
  1. //默认参数
  2. function fun(s:string="hello world"):string{
  3. console.log(s);
  4. return s;
  5. }
  6. fun("good");
  1. //返回值是任意类型
  2. function func(s:any):any{
  3. return s;
  4. }

  1. class Person{
  2. //实例的name
  3. name:string
  4. age:number
  5. constructor(name:string,age:number){
  6. this.name=name;
  7. this,age=age;
  8. }
  9. getName():void{
  10. console.log(Person.name)
  11. console.log(this.name);
  12. }
  13. }
  14. var p:Person = new Person("cheng",20);
  15. p.getName();
  1. class Person{
  2. /* 实例的name */
  3. name:string
  4. age:number
  5. getName():void{
  6. console.log(this.name);
  7. }
  8. }
  9. var p:Person = new Person();
  10. p.getName();
  11. //当没有构造函数的时候,代码底层有自动补全构造函数

4-1 static

  1. //static修饰的变量是类所共有的,只能通过类名去调用。
  2. class Person{
  3. /* 实例的name */
  4. static skill:string = "js";
  5. name:string
  6. age:number
  7. getName():void{
  8. console.log(Person.skill)
  9. console.log(this.name);
  10. }
  11. }
  12. var p:Person = new Person();
  13. p.getName();

5-1定义一个泛型函数

好处:兼顾了灵活性和类型检查

  1. function goTest<T>(s:T):T{
  2. return s;
  3. }
  4. goTest<string>("1000");
  5. goTest<number>(100);