puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

04. Interface in Typescript #25

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

Similar to the Abstract Class in ES5, while it has more.

Interface can define type, function, class, etc.

Property Interface

to constrain behavor and batch of methods, and also JSON

interface fullName{
    firstName: string;
    lastName: string;
}

function printName(name: fullName) {
   console.log(name.firstName+'---'+name.lastName);
}

// senario 1          // fail, age is extra
printName({
    age:20,
    firstName:'shawn',
     lastName:'Wu',
})

/// senario 2       // pass, cause the object is defined outside
var obj = {
    age:20,
    firstName:'shawn',
     lastName:'Wu',
}
printName(obj);

Optional Properties

interface fullName{
    age ?: number;
    firstName: string;
    lastName: string;
}

An example in ajax


**************
$.ajax({
   type:"GET",
   url:"test.json",
   data: {username:$("#username").val(), content:$("#content").val()},
   dataType: "json",
})
**************

interface Config{
   type:string;
   url:string;
   data?:string;
   dataType:string;
}

function ajax (config: Config) {
   var xhr = new XMLHttpRequest ( );
   xhr.open (config.url, config.url, true);
   xhr.send ( config.data );
   xhr.onreadystatechange = function (){
       if (xhr.readystate === 4 && xhr.status === 200){
               console.log('success');

              if(config.dataType === 'json') {
                     JSON.parse(xhr.responseText)
              }else{
                     console.log(xhr.responseText)
               }
        }
  }
}

ajax({
   type: 'get',
   url:'http://www.baidu.com',
   dataType:'json',
})

Function Interface

To constrain the passed parameters, and returned values, and patches;

encrypt function interface

interface Encrypt{
   (key:string, value:string):string;
}

var md5: Encrypt = function (key:string, value:string):string{
    return key+'-'+value;
}

md5('name','shawn'); // name-shawn

Indexable Interface

To constrain Array, Objects, not common,

interface UserArr{
   [index:number]:string;
}

var arr:UserArr = ['aaa','bbb'];
arr[0]; // 'aaa'
interface UserObj{
    [index:string]:string;
}

var arr:UserObj = {name:'shawn'};

Class Type Interface

To constrain Class, similar to Abstract Class.

interface Animal{
   name:string;
   eat(str:string):void;
}

class Dog implements Animal{
   name:string;
   constructor(name:string){
         this.name = name;
   }

    eat(){ console.log('Eat Meat');      // ===> Without implementing this method, would be wrong
}

var d = new Dog('Huang');
d.eat();  // Huang Eat Meat

Without implementing this eat( ) method, would be wrong, but passing parameters is only optional.

Interface Inherits Interface

extends

interface Animal{
   eat():void;
}

interface Person extends Animal{
   work():void;
}

class Web implements Person{
   public name:string;
   constructor(name:string){
        this.name = name;
    }

     eat(){console.log('Eat Meat')};
     work(){console.log('Write Code')};
}

var w = new Web('shawn');
w.work(); // shanw Write Code

-extending another Class at the same time

interface Animal{
   eat():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{

   constructor(name:string){
        super(name);
    }

     eat(){console.log('Eat Meat')};
     work(){console.log('Write Code')};
}

var w = new Web('shawn');
w.coding('writes TS');  // shanw writes TS;