Typescript in the interface _javascript skills

Source: Internet
Author: User

In typescript, interfaces are used as constraints, and when translated into JavaScript, all interfaces are wiped out because JavaScript does not have the concept of interfaces.

Let's take a look at a simple example:

function Printlabel (labelledobj: {label:string}) {
  console.log (Labelledobj.label);
}

var myobj = {size:10, Label: "Size Ten Object"};
Printlabel (myobj);

So in this method, the type of Labelledobj is {label:string}, which may seem a bit complicated, but we see a look at the MyObj statement below to see that it declares an owning Size property (value 10) and a label property (value of size 10 Object "). Therefore, the type of the method parameter labelledobj is {label:string}, which indicates that the parameter has a String Type label property.

But, in so doing, this approach still seems a bit confusing. You can then use an interface (interface) to define the parameter type of this method.

Interface Labelledvalue {
  label:string;
}

function Printlabel (labelledobj:labelledvalue) {
  console.log (Labelledobj.label);
}

var myobj = {size:10, Label: "Size Ten Object"};
Printlabel (myobj);

Optional properties
Sometimes, we do not need the attribute to exist, we can use the attribute of optional attribute to define.

Interface Squareconfig {
  color?: string;
  Width?: number;
}

function Createsquare (config:squareconfig): {color:string area:number} {
  var newsquare = {color: ' White ', area: };
  if (config.color) {
    newsquare.color = Config.color;
  }
  if (config.width) {
    Newsquare.area = config.width * config.width;
  }
  return newsquare;
}

var mysquare = createsquare ({color: "BLACK"});

Then we pass on the object into the Createsquare method that implements a Squareconfig interface.

Since it is completely dispensable, why should it be defined? There are two advantages to defining optional attributes, compared to completely undefined. 1, if there are attributes, can constrain the type, this is very critical; 2, can get the syntax intelligent hint, if the method body in the wrong color written Collor, then compile is not passed.

Method type

In JavaScript, method function is a basic type. In object-oriented thinking, the implementation of interfaces is done by classes, and function as a type, is it possible to implement interfaces? The answer is yes.

In typescript, we can use interfaces to constrain the signature of a method.

Interface Searchfunc {
 (source:string, substring:string): boolean;
}

var Mysearch:searchfunc;
Mysearch = function (source:string, substring:string) {
 var result = Source.search (subString);
 if (result = = 1) {return
  false;
 }
 else {return
  true;
 }
}

In the code above, we define an interface that constrains the signature of a method, which has two string arguments, and returns a Boolean value. In the second piece of code we declare the implementation of this interface.

It should be noted that the compiler simply checks whether the type is correct (parameter type, return value type), so the name of the parameter can be changed to something else.

var Mysearch:searchfunc;
Mysearch = function (src:string, sub:string) {
 var result = Src.search (sub);
 if (result = = 1) {return
  false;
 }
 else {return
  true;
 }
}

This is also able to compile the pass.

Array type
In the above we define the method type in the interface, then how should the array type be defined? Very simple.

Interface Stringarray {
 [index:number]: string;
}

var Myarray:stringarray;
MyArray = ["Bob", "Fred"];

So myarray is an array, and the indexer is number type, and the element is string.

In the definition of an interface, the name of the indexer is usually index (which can, of course, be changed to something else, but it usually keeps the name index). So change it into

Interface Stringarray {
 [myindex:number]: string;
}

var Myarray:stringarray;
MyArray = ["Bob", "Fred"];

It's OK, too.

It should be noted that the type of the indexer can only be number or string.

Interface array{
  [index:number]: any;
}

Interface dictionary{
  [index:string]: any;
}

The above two paragraphs can be compiled through.

Finally, it is important to note that if the interface is already an array type, the types of other properties defined in the interface must be of the element type of the array. For example:

Interface Dictionary {
 [index:string]: string;
 Length:number;  Error, the type of ' length ' is not a subtype of the ' indexer
}

Then you will not be able to compile the pass and you need to change the length to a string type.

Implementing interfaces using classes
In general, we are still accustomed to using a class to implement the desired interface, rather than using the interface directly as above.

Interface Clockinterface {
  currenttime:date;
}

Class Clock implements Clockinterface {
  currenttime:date;
  Constructor (H:number, M:number) {}
}

In typescript, the class keyword is used to declare, which is the same as EcmaScript 6.

In addition, we can use interfaces to constrain the methods defined in the class.

Interface Clockinterface {
  currenttime:date;
  SetTime (d:date);
}

Class Clock implements Clockinterface {
  currenttime:date;
  SetTime (d:date) {
    this.currenttime = D;
  }
  Constructor (H:number, M:number) {}
}

In typescript, we can define constructors for interfaces.

Interface Clockinterface {
  new (hour:number, minute:number);
}

The next naïve we might go on to write this:

Interface Clockinterface {
  new (hour:number, minute:number);
}

Class Clock implements Clockinterface {
  currenttime:date;
  Constructor (H:number, M:number) {}
}

It's not going to work,!!!. Because constructors are static (static), a class can only implement the instance (instance) portion of an interface.

So is the constructor defined in this interface not useful? Since typescript provides this functionality, it certainly won't work. The method of declaring is more special:

Interface Clockstatic {
  new (hour:number, minute:number);
}

Class Clock {
  currenttime:date;
  Constructor (H:number, M:number) {}
}

var cs:clockstatic = Clock;
var newclock = new CS (7, 30);

Normally we write new Clock, where we point the Clock class to the Clockstatic interface. It should be noted that the type of the Newclock variable is any.

Inheriting interfaces
Like a class, an interface can also implement inheritance, using the extends keyword.

Interface Shape {
  color:string;
}

Interface Square extends Shape {
  sidelength:number;
}

var square = <Square>{};
Square.color = "Blue";
Square.sidelength = 10;

Of course, you can inherit multiple interfaces.

Interface Shape {
  color:string;
}

Interface Penstroke {
  penwidth:number;
}

Interface Square extends Shape, penstroke {
  sidelength:number;
}

var square = <Square>{};
Square.color = "Blue";
Square.sidelength = ten;
Square.penwidth = 5.0;

It is to be noted that, although support inherits multiple interfaces, it cannot be compiled if the inherited interface has a different type of property with the same name as the definition.

Interface Shape {
  color:string;
  Test:number;
}

Interface Penstroke {
  penwidth:number;
  test:string;
}

Interface Square extends Shape, penstroke {
  sidelength:number;
}

Then the code cannot be compiled because the type of the test property cannot be determined.

Use the same type as described above
If only a single type can be used, then the interface is too weak. But luckily, our interface is very powerful.

Interface Counter {
  (start:number): string;
  Interval:number;
  Reset (): void;
}

var C:counter;
(c);
C.reset ();
C.interval = 5.0;

This makes use of the three types, which are the methods (the interface itself is a method), the property, the method (the method member is defined).

The above mentioned is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.