typeScrpt 入门

接口:方法使用

//方法里面可以直接使用接口
interface Person {//定义一个接口,接口里面所有参数的类型都可以指定
    firstName: string;
    lastName: string;
}

function greeter(person: Person) {//用这个接口来规范传参
    return "Hello, " + person.firstName + " " + person.lastName
}

greeter('jack', 'rose')//正确
greeter(1,1)//报错,传参类型不匹配

接口 类使用

//类使用接口  implements 来使用接口  

/**
 * 只做类型定义,不写具体实现,要在使用的地方再次定义,并写实现,并且不能遗漏接口里面已经定义好的参数
 */
interface ClockInterface {
    currentTime: Date;
    getTime(d: Date);
}

class Clock implements ClockInterface {
    currentTime: Date;
    constructor(h: number, m: number) {
        console.log(h+':'+m)
    }
    getTime(d: Date){//申明为时间类型 new Date(),如果使用Date类型,必须这种形式传入
        console.log(d)
    }
    test(a: number){
        console.log(a)
    }
}

let p = new Clock(12, 30);
let date = new Date()//可以存为变量形式来传值
p.getTime(date)
p.test(123)

private protected public

/**
 * 1.private: 外部不能访问,继承后,也仅能父级访问,子类仍然无法访问
 * 2.protected: 外部不能访问,继承后,子类可以访问
 * 3.public: 标明成员公开的
 */
class Animal {
    protected name: string; // 如果这里protected  改为 private 那么下面的AllClass继承后,仍然不可访问name
    protected constructor(theName: string) {
        this.name = theName;
        console.log(this.name);
    }
}

class AllClass extends Animal {//继承了Animal
    private age: number;
    constructor(name: string, age: number) {
        super(name);
        this.age = age;
    }
    public getNAndA(){
        console.log('name:', this.name, 'age:', this.age);
    }
}

let p = new Animal('小鸡');
p.name//报错,外部不能访问

let p2 = new AllClass('小鸡', 1);
p2.getNandA()//name: 小鸡 age: 1  可以访问Animal的name  
p2.age//报错,外部不能访问

函数有返回值

/**
 * 1.如果函数有返回值那么void应改为相应返回值的类型,比如:number,string
 * 2.如果函数没有返回值,那么返回值类型为 void
 * 3.方法里面的参数会根据上下文自动识别类型
 */
let myAdd: (one:number, two: number) => number= function(x:number, y:number) {
    retrun x+y
}
myAdd(222,333)

函数没有返回值

//function里面的变量类型申明可以省略
let myAdd: (one:number, two: number) => void = function(x, y) {
    console.log(x+y)
}
myAdd(222,333)

已知参数个数 1.?可选参数 2.默认参数

let buildName: (firstName: string, lastName?: string) => string = function (x, y='xxxx') {
    if(y) 
        return x + '' + y
    else
        return x
}

console.log(buildName('流弊'))// 流弊xxxx

未知参数个数

let buildNames: (firstName: string, ...restOfName: string[]) => string = function(x, ...y){
    return x + " " + y.join(" ");
}

let a = buildNames('x', 'y', 'z', 'k')
console.log('拼接的字符串:', a)//拼接的字符串: x y z k
原文地址:https://www.cnblogs.com/yzyh/p/10406585.html