观看bilibili的视频总共总结了三篇文章(入门一,二,三);每一篇的内容都是同一类型的,这样理解起来更加方便;之后我回去找一些其他的TypeScript的资料去更加深入的学习一下;
(1)typeScript接口:
typescript中的接口类似于java,同时还增加了更灵活的接口类型,包括属性、函数、可索引和类等;
//1.ts自定义方法传入参数,对json进行约束
function printLable(labelInfo:{label:string}):void{console.log('haha')}
printLabel({label:'xiaoming '}); //必须包含label
//2.对批量方法传入参数进行约束
interface FullName{
firstName: string;
secondName: string;
}
function printName(name:FullName){
console.log(name.firstName)
}
var obj = {
age:20,
firstName: 'xiao',
secondName: 'san'
}
printName(obj);//若直接将对象写入参数中,那么只能包含firstName和secondName;
//3.接口可选属性
interface FullName{
firstName: string;
secondName?: string;
}
//函数类型接口: 对方法传入的参数以及返回值进行约束 和批量约束
//加密的函数类型接口
interface encrypt{
(key:string,vakue:string):string;
}
var md5:encrypt = function(key:string,vakue:string):string{
//模拟操作
return key + value;
}
console.log(md5('name': 'xiaoming'));
var sha1:encrypt = function(key: string,value: string): string{
return key+'--'+value;
}
console.log(sha1('name': 'xiaoming'));
//可索引接口;数组,对象的约束(不常用)
interface UserArr{
[index:number]:string
}
var arr: UserArr = ['aa','bb'];
console.log(arr[0]);
interface UserObj{
[index:string]:any
}
var obj:UserObj = [name:'12'];
//类类型接口:对类的约束 和 抽象类有点相似
interface Animal{
name:string;
eat(str:string):void;
}
class Dog implements Animal{
name: string;
constructor(name:string){
this.name = name
}
eat(){ //不添加就会报错
console.log(this.name + "吃狗粮 ");
}
}
var d = new Fog('二哈');
d.eat();
//接口扩展: 接口可以继承接口
interface Animal{
ear(): void;
}
interface Person extends Animal{
work():void;
}
class Programmer{
public name: string;
constructor(name:string){
this.name = name;
}
coding(code:string){
console.log(this.name + code)
}
}
class Web extends Programmer implements Person{
public name: string;
constructor(name:string){
this.name = name;
}
eat(){
console.log(this.name + '喜欢吃')
}
work(){
console.log(this.name + '喜欢写')
}
}
var w = new Web('xiaoming');
w.coding('写代码');
越看越觉得跟jave和c#有相似之处,有空的话也要捡起来我的java啊,后续再说...