ts随笔

在react安装

npm install react-router-dom --save //路由

npm install axios --save //axios

 
npx create-react-app my-app --template typescript --use-npm 
 

npx :避免安装模块 ,调用 项目中模块

 

配置

quote TypeScript › Preferences: Quote Style--single

tab :

 

Prettier - Code formatter 插件:

save :

安装

npm install typescript@3.6.4 -g

tsc 名字.ts //转为js

 

 

npm install -g ts-node

ts-node demo.ts // 运行

 

在浏览器运行

 
 
npm init -y
tsc-init
 创建src目录- page.ts
编辑tsconfig.json
其中rootDir  编译的文件目录  ‘./src’
出口outDir   ‘./dist’
最外层创建index.html
<body>
  <script src='./dist/page.js'></script>
</body>
tsc -w 监听模式
 

 


ts基本语法

类型

 
 
const count: number = 2020;
let temp: number | string = 123;
temp = "asd";
//对象类型
interface Point {
  x: number;
  y: number;
}
const point: Point = {
  x: 3,
  y: 4,
};
point.x
 
 
 
 
 
 
 
 
const teacher:{
    name:string;
    age:number
}={
    name:'Dell',
    age:18
};
const numbers:number[]=[1,2,3]  //正确
const numbers:number[]=[‘123’,2,3]  //错误
 
 
 
 
 
 
 
 
class Person {}
const dell:Person =new Person();
const getTotal: () => number = () => {
  return 1523;
};
 

类型推断

 
 
 
 
 
 
 
function getTotal(firstnumber: number, secondnumber: number) {
  return firstnumber + secondnumber;
}
getTotal(123, 546);
 

函数相关类型

 
 
 
 
 
 
 
// 函数相关类型
// function hellow() {}
// const hellow = function () {};
function getTotal(firstnumber: number, secondnumber: number): number {
  return firstnumber + secondnumber;
}
getTotal(123, 546);
function satHello(): void {
  // void返回空  不允许有返回值
  console.log("hello");
}
function errorEmitter(): never {
  //无限执行
  // throw new Error();
  while (true) {}
}
// 解构赋值类型写法
function add({ first, second }: { first: number; second: number }): number {
  return first + second;
}
add({ first: 1, second: 2 });
//函数声明
function App   x:number,y:string,z:number=10){}
 

数组和元组

 
 
 
 
 
 
 
// 数组和元组
const arr: (number | string | {})[] = [1, 2, 3, "sad", { name: "223" }];
type User = { name: string; age: number };
const objectArr: User[] = [
  {
    name: "dell",
    age: 28,
  },
];
class Teacher {
  name: string;
  age: number;
}
const objteacther: Teacher[] = [
  new Teacher(),
  {
    name: "Lily",
    age: 20,
  },
];
// 元组   约束内容   
const teacherInfo: [string, string, number] = ["Dell", "male", 20];
 

接口interface

 
 
 
 
 
 
 
type name = string; //类型别名直接可以代表一个类型
interface Person {
  name: string; //   readonly 只读无法修改
  age?: number; //可有可无
  [propName: string]: any;
  say(): string;
} //接口 代表函数对象
interface Teacher extends Person {
  //继承
  teach(): string;
}
// ---------------------
const getPersonName = (person: Person): void => {
  console.log(person.name);
};
const setPesonName = (person: Teacher, name: string): void => {
  person.name = name;
};
const person = {
  name: "dell",
  sex: "male",
  say() {
    return "say";
  },
  teach() {
    return "sas";
  },
};
getPersonName(person);
// getPersonName({
//   name: "dell",
//   sex: "male",
// });
setPesonName(person, "lee");
// -------------
class UserA implements Person {
  //类去应用接口
  name = "dell";
  say() {
    return "hellow";
  }
}
// -----------------------
interface SayHi {
  //函数类型
  (word: string): string;
}
const say: SayHi = (word: string) => {
  return "word";
};
 

类的继承

 
 
 
 
 
 
 
(function () {
  class Person {
    name = "dell";
    getName() {
      return this.name;
    }
  }
  class Teacher extends Person {
    getTeacherName() {
      return "teacher";
    }
    getName() {
      //重写  在子类中
      // return "newdell";
      return super.getName() + "newdell";
      //super 调用父类方法
    }
  }
  const person = new Person();
  console.log(person.getName());
  const teacher = new Teacher();
  console.log(teacher.getName());
  console.log(teacher.getTeacherName());
})();
 

public-private-protected

 
 
 
 
 
 
 
(function () {
  // public 允许我在类内外被调用
  //private  允许在类内被使用
  // protected 允许在类内及继承的子类中使用
  (function () {
    class Person {
      public name: string;
      public sayHi() {
        console.log("hi");
      }
      private sayABC() {
        this.name;
      }
    }
    class Teacher extends Person {
      sayBye() {
        this.name;
      }
    }
    const person = new Person();
    person.name = "dell";
    console.log(person.name);
    person.sayHi();
  });
  // -----------------------------------
  // class Person {
  //   // public name: string;
  //   constructor(public name: string) {
  //     // this.name = name;
  //   }
  // }
  // const person = new Person("dell");
  // console.log(person.name);
  class Person {
    constructor(public name: string) {}
  }
  class Teacher extends Person {
    constructor(public age: number) {
      super("dell"); //调用父类
    }
  }
  const teacher = new Teacher(28);
  console.log(teacher.name);
})();
 

setter -getter /单列

 
 
 
 
 
 
 
(function () {
  class Person {
    constructor(private _name: string) {}
    get name() {
      //设置
      return this._name + "lee";
    }
    set name(name: string) {
      //改
      const realName = name.split(" ")[0];
      this._name = realName;
    }
  }
  const person = new Person("dell");
  console.log(person.name);
  person.name = "delsl lee";
  console.log(person.name);
})();
//单例模式
class Demo {
  private static instance: Demo;
  private constructor(public name: string) {}
  static getInstance() {
    if (!this.instance) {
      this.instance = new Demo("dell lee");
    }
    return this.instance;
  } //static  挂载到demo 而不是实例
}
const demo1 = Demo.getInstance();
const demo2 = Demo.getInstance();
 

抽象类 -接口interface 继承

 
 
 
 
 
 
 
(function () {
  // class Person {
  //   public readonly name: string; //readonly  只读
  //   constructor(name: string) {}
  // }
  // const person = new Person("dell");
  // // person.name = "hello";
  // console.log(person.name);
  // -------------------------------------
  //抽象类
  abstract class Geom {
    //抽象类只能被继承
    width: number;
    getType() {
      return "Gemo";
    }
    abstract getArea(): number;
  }
  class Circle extends Geom {
    getArea() {
      return 123;
    }
  }
  // ----------------------
  interface Person {
    name: string;
  }
  interface Teacher extends Person {
    teachingAge: number;
  }
  interface Student extends Person {
    age: number;
  }
  interface Driver {
    name: string;
    age: number;
  }
  const teacher = {
    name: "dell",
    teachingAge: 3,
  };
  const student = {
    name: "lee",
    age: 18,
  };
  const getUserInfo = (user: Person) => {
    console.log(user.name);
  };
  getUserInfo(teacher);
})();
 

 

语法进阶

类型断言/类型保护

 
 
 
 
 
 
 
(function () {
  interface Bird {
    fly: boolean;
    sing: () => {};
  }
  interface Dog {
    fly: boolean;
    bark: () => {};
  }
  //类型断言
  function trainAnial(animal: Bird | Dog) {
    //联合类型
    if (animal.fly) {
      (animal as Bird).sing();
    } else {
      (animal as Dog).bark();
    }
  }
  //in 语法
  function trainAnialSecond(animal: Bird | Dog) {
    if ("sing" in animal) {
      animal.sing();
    } else {
      animal.bark();
    }
  }
  function add(first: string | number, second: string | number) {
    if (typeof first === "string" || typeof second === "string") {
      return `${first}${second}`;
    }
    return first + second;
  }
  class NumberObj {
    count: number; //instanceof
  }
});
 

枚举

 
 
 
 
 
 
 
//枚举
enum Status {
  OFFLINE,  //默认为0
  ONLINE,
  DELETED,
}
// enum Status {
//   OFFLINE=2,
//   ONLINE,   //3
//   DELETED,   //4
// }
console.log(Status.DELETED);
console.log(Status[0]);  //ODDLine
 

泛型基础

 
 
 
 
 
 
 
// function  join(first:string|number,second:string|number) {
//   return `${first}${second}`
// }
// join(1,1)
// 泛型
function join<ABC>(first: ABC, second: ABC) {
  return `${first}${second}`;
}
join<string>("1", "2"); //<number>
function map<ABC>(params: ABC[]) {
  return params;
}
map<string>(["2", "ss"]);
function joinA<ABC, DEF>(first: ABC, second: DEF) {
  return `${first}${second}`;
}
joinA<string, number>("1", 2); //<number>
// 类中使用泛型
interface Item {
  name: string;
}
class DataManager<asd extends Item> {
  //继承Item所有属性
  constructor(private data: asd[]) {}
  getItem(index: number): string {
    return this.data[index].name;
  }
}
const data = new DataManager([{ name: "dell" }]);
data.getItem(0);
// 声明类型   使用泛型作为一个具体的类型注解
function hello<T>(params: T) {
  return params;
}
const func: <T>(param: T) => T = hello;
// const func: <ABC>(param:ABC) => string = <ABC>() => {
//   return "123";
// };
        
        // 泛型约束
  interface IWithlength{
     length:number
  }
function name<T extends IWithlength>(arg:T):T {
   console.log(arg.length)
   return arg
  }
  const arrs=name([1,2,3])
 const arrd=name({length:10,width:10})
  const str=name('str')
 

namespace

namespace Components {
  export class Header {
    constructor() {
      const elem = document.createElement("div");
      elem.innerHTML = "This is Header";
      document.body.appendChild(elem);
    }
  }

  export class Content {
    constructor() {
      const elem = document.createElement("div");
      elem.innerHTML = "This is content";
      document.body.appendChild(elem);
    }
  }

  export class Footer {
    constructor() {
      const elem = document.createElement("div");
      elem.innerHTML = "This is Footer";
      document.body.appendChild(elem);
    }
  }
}
namespace Home {
  //命名空间

  export class Page {
    //把page输出 暴露出去
    constructor() {
      new Components.Header();
      new Components.Content();
      new Components.Footer();
    }
  }
}

泛型keyof

interface Person {
  name: string;
  age: number;
  gender: string;
}
// type T = "name";
// key: 'name';
// Person['name'];

// type T = 'age'
// key: 'age';
// Person['age']

class Teacher {
  constructor(private info: Person) {}
  getInfo<T extends keyof Person>(key: T): Person[T] {
    return this.info[key];
  }
}
const teacher = new Teacher({
  name: "dell",
  age: 18,
  gender: "male",
});
const test = teacher.getInfo("age");
console.log(test);

 

posted @ 2020-07-28 09:23  陶智斌  阅读(203)  评论(0编辑  收藏  举报