TypeScript(下)

42 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 3 天,点击查看活动详情

几天的时间终于把ts的基本语法过了一遍了,学ts后面感觉和Java差不多,可能这些语言就是互相借鉴的吧。

  • 抽象类和类的类型

    abstract用于定义抽象类和其中的抽象方法

    抽象类不能被实例化,抽象方法不能具体实现

    主要用于对子类的服务

    在子类中去具体实现抽象类中的抽象方法

类与接口

  • 类实现接口
interface Sing{
    sing()
}
interface Dance{
    dance()
}
class P implements Sing,Dance{
    sing() {
        console.log("sing")
    }
    dance() {
        console.log("dance")
    }
}
class An implements Sing,Dance{
    sing() {
        console.log("sing")
    }
    dance() {
        console.log("dance")
    }
}
const p1 = new P()
const p2 = new An()
p1.sing()
p2.sing()
p1.dance()
p2.dance()
  • 接口继承接口,类实现接口

    interface Run{
        run()
    }
    interface Swim{
        swim()
    }
    interface Sport extends Run,Swim{
    ​
    }
    class S implements Sport{
        run(){
            console.log("run")
        }
        swim() {
            console.log("swim")
        }
    }
    const person = new S()
    person.run()
    person.swim()
    
  • 接口继承类

    class Person{
        name:string
        constructor(name){
            this.name = name;
        }
    }
    interface person extends Person{
    ​
    }
    let x:person = {name:""}
    

    接口继承类的属性和方法

声明合并

如果定义了两个相同名字的函数,接口或类,那么他们会合并成一个类型。

  • 接口的属性在合并时会简单的合并到一个接口中

    interface people{
        name:"hhh"
    }
    interface people{
        name:"hhh"
        age:12
    }
    

泛型

泛型是指在定义函数、接口或类的时候,不预先指具体的类型,而在使用的时候在指定类型的一种特效。

  • T表示任意输入的类型
function getArr<T>(value:T,count:number): T[] {
    const arr:T[]=[];
    for(let i = 0; i < count; i ++)
    {
        arr.push(value)
    }
    return arr;
}
console.log(getArr(200,3));
console.log(getArr("xx",3));
  • 多个泛型参数

    function updateArray<T,U>(t:[T,U]){
        return [t[1],t[0]];
    }
    ​
    console.log(updateArray([123,"xxx"]))
    
  • 泛型约束

    interface ILength {
        length:number
    }
    function getLength<T extends ILength>(x:T):number{
        return x.length;
    }
    console.log(getLength("hhhhh"));
    

泛型接口和泛型类

  • 泛型接口
interface IArr{
    <T>(value:T,count:number):Array<T>
}
let getArr = function<T>(value:T,count:number):T[]{
    const arr = [];
    for(let i = 0; i < count; i ++){
        arr.push(value)
    }
    return arr;
}
console.log(getArr("22",4));
  • 泛型类

    class Person<T>{
        name:T
        age:T
        constructor(name:T,age:T){
            this.name = name;
            this.age = age
        }
    }
    let p1 = new Person<number>(12,2)
    let P2 = new Person<string>("ls","12")