一文带你了解typeScript的使用

136 阅读3分钟

一、基本数据类型

// 字符串
let str:string = '字符串'; //声明赋值可以不用加类型,ps:str = '字符串';

//数字
let num:number = 1000; 

//布尔
let boo:boolean = false;

//空值
let unusable:void = undefined;

//null
let n:null = null;

//undefined
let un: undefined = undefined;

//any
let test:any = true; //不建议失去了any的意义

二、数组、元组、枚举、联合类型

//数组
let arr:number[] = [1,2,3,4,5,6]; //数组里面只能是number类型,可以进行数组操作,但必须是number类型
ps:arr.push(32); // arr=[1,2,3,4,5,6,32]

//元组:合并了相同类型或不同类型的对象
let tom:[string,number] = ['字符串',123];
let tom1:[string,number];
tom[0] = 'tom';
tom[1] = 23;
tom[0].slice(1);
tom[1].toFixed(2);


//枚举
// 普通枚举
enum liveStatus {
    SUCCESS = 0;
    FAIL = -1;
    USEING = 1;
}
const res = LiveStatus.FAIL;
enum Days {
    Sun,Mon,Tue,Wed
}
console.log('Days',Days.sun === 0); // true
// 常数枚举
const enum Directions {
    Up,
    Down,
    Left,
    Right
}
console.log(Directions.Up); // true 
//外部枚举
declare enum Dire = {
   Up,
   Down,
   Left,
   Right
}
let dir1 = [Dire.Up,Dire.Down,Dire.Left,Dire.Right];
console.log(dir1); // [0,1,2,3]

//Union
let aaa:number | string;
aaa = 1000;
aaa = '字符串';

三、接口interface

interface 可以继承、扩充

// 首字母要大写,一般建议以I开头
interface IPerson = {
    name : string,
    age : number
}
// 多一个少一个属性或者类型不对,都会报错,必须跟申明的接口类型和属性一致
//正常
let jack:IPerson = {
    name : 'jack',
    age : 25
}
//报错 多了一个属性
let jack1:IPerson = {
    name : 'jack',
    age : 25,
    a: 1 // 多了属性
}
//报错,属性值类型不对
let jack2:IPerson = {
    name : 'jack',
    age : '25', //数字类型
}

//可选属性
interface IPerson2 = {
    name : 'jack',
    age? : 25 //可选属性
}
//正常
let jack3:IPerson2 = {
    name : 'jack'
}

//任意属性
interface IPerson3 = {
    name : 'jack',
    age : 25, 
    [propName:string] : string | number //任意属性
}

//只读属性
interface IPerson4 = {
    readonly id : number,
    name : string,
    age : number
}
let jack4:IPerson4 = {
    id: 1,
    name : '张三',
    age : 25
}
jack4.id = 333; // 报错

四、type

type 不可以重复声明,interface 可以

type Card = {
    name: string
}

type Card = {} //报错

五、Function

// 函数声明
function sum (x:number,y:number){
    return x + y;
}

//函数表达式
let mySum = function(x:number,y:number){
    return x + y;
}
sum(1,2);
sum(1,2,3) //报错 参数多了
sum(1) //报错 参数少了

//函数表达式--箭头函数
let mySum: (x:number, y:number) => number =  function(x:number,y:number){
    return x + y;
}

// 不要混淆 typescript中的 => 和 es6 中的=>

//可选参数
function buildName(firstName:string,lastName?:string){
    if(lastName){
        return firstName + lastName;
    }else {
        retrun firstName
    }
}

//参数的默认值
function buildName2(firstName:string,lastName:string = 'jack'){
    return firstName + lastName;
}
let tomcat = buildName2('tom','cat'); //tomcat

//剩余参数 
//...rest
function push(arry: number[],...items:number[]){
    items.forEach(function(item){
        arry.push(item);
    })
}

//函数重载 一个函数接收不同数量、不同类型的参数,做出不同的处理
function reverse(x:number):number;
function reverse(x:string):string;
function reverse(x:number | string):number | string | void{
    if(typeof x === 'number'){
       return Number(x.toString().split('').reverse().join('')); 
    } else if(typeof x === 'string'){
       return x.split('').reverse().join('');
    }
}

六、断言

interface Data{
  userId: number,
  id: number,
  title: string,
  completed: boolean
}

async function getData(){
    const res = await fetch("www.baidu.com");
    const data = await res.json() as Data()
}

const data1:Data = {
  userId: 1,
  id: 2,
  title: 'abc',
  completed: true
}

interface Beta {
  name: string
}
const beta = data1 as unknown as Beta;

七、class

class Animal {
    public name;
    constructor(name:string){
        this.name = name;
    }
    sayHi(){
        return `my name is ${this.name}`
    }
}
let a = new Animal('jack');

//继承
class Cat extends Animal {
    constructor(name:string){
        super(name); //父类的constructor
        console.log(this.name);
    }
    sayHi():string {
        return 'my name is ' + super.sayHi(); //调用了父类的sayHi
    }
}
let c = new Cat('jack');

//静态方法和属性
class Animal1 {
    static num = 123;
    static isAnimal(a:Animal){
        return a instanceof Animal;
    }
}
Animal1.isAnimal(a);
//修饰符
//public:默认就是public 可以继承和实例化 可以修改
//private:不能继承和实例化,不能外部访问
//protected:可以继承不能实例化,不能外部访问
//readonly:可以继承和实例化,不能修改

//抽象类 abstract 不允许被实例化 不能new
abstract class Animal3{
    name;
    constructor(name:string){
        this.name = name;
    }
    abstract public sayHi():void;
}

//抽象类中的抽象方法必须被子类实现
class Cat3 extends Animal3 {
    eat(){
        console.log('吃东西');
    }
    sayHi(){
        // 不去实现的话 会报错
    }
}

//类的类型
class Animal4 {
    name;
    constructor(name:string){
        this.name = name;
    }
}
let a4:Animal4 = new Animal4('panda');

八、泛型

 function createArray<T>(len:number,value:T):Array<T>{
     let res: T[] = [];
     for(let i =0; i<len; i++){
         res[i] = value;
     }
     return res
 }
 createArray(3, 'x');
 //泛型约束 
 interface Len{
    length: number
 }
 
 function log<T extends Len>(arg:T):T{
     console.log(arg.length);
     return arg;
 }

九、class 与 interface

interface Alarm {
    alert():void;
}

class Door {
    
}

class SDoor extends Door implements Alarm {
    alert():void{
        console.log(SDoor slert);
    }
}

class car implements Alarm{
    alert(): void{
        console.log('Car alert');
    }
}

interface Light{
    alert():void;
    on():void;
    off():void;
}
//接口和接口之间也可以继承
interface LightAlarm extends Alarm {
   on():void;
   off():void;
}

//接口可以继承类
class Point{
    x:number,
    y:number,
    constructor(x:number,y:number){
        this.x = x;
        this.y = y;
    }
}
interface Point3D extends Point{
    z:number
}
let point3d: point3D = {x:1,y:2,z:3};
let p = new Point(1,2);
function printPoint(p:Point){
    console.log(p.x,p.y);
}
interface PointType{
    x:numbere,
    y:numebr
}
function printPoint1(p:PointType){
    console.log(p.x,p.y);

interface Point3D1 extends Point{}
interface Point3D1 extends PointType{
   z:number 
}

十、Utility、Pick、Omit

interface CatInfo{
    age:number;
    breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
//第一个参数是key
//第二个参数是value
const cats:Record<CatName,CatInfo> = {
    miffy: {age:10 , breed:"Person"},
    boris: {age 5 , breed: "Maine Coon"},
    mordred: {age: 16, breed: "British Shorthair"}
}

//pick
interface Todo{
    title: string;
    description: string;
    completed: boolean;
}

type TodoPreview = Pick<Todo, "title" | "completed">;

const todo:TodoPreview = {
    title: "Clean room",
    completed: false,
}

//Omit
interface Todo2{
    title: string;
    description: string;
    completed: boolean;
    createdAt: number;
}

type TodoPreview2 = Pick<Todo2, "description">;

const todo2:TodoPreview2 = {
    title: "Clean room",
    completed: false,
    createdAt: 16155441452
}

//declear
//jquery  $
ceclare var $: {selector:string} => any;
$("#id")
//声明文件 .d.ts 结尾
//@types