Interface Details in TypeScript

Source: Internet
Author: User

Interface Details in TypeScript

One of the core design principles of TypeScript is the type check, which can be checked through Interfaces to satisfy the traditional Object-oriented Thinking, facilitate effective development and effectively avoid type conversion problems.

In TypeScript, interfaces are used as constraints. When compiled into JavaScript, all interfaces are erased because JavaScript does not have interfaces.

Let's take a look at a simple example:

?

1

2

3

4

5

6

Function printLabel (labelledObj: {label: string }){

Console. log (labelledObj. label );

}

 

Var myObj = {size: 10, label: "Size 10 Object "};

PrintLabel (myObj );

In this method, the labelledObj type is {label: string}, which may seem a bit complicated, but we can see the following myObj declaration, this is an Object with the size attribute (value: 10) and label attribute (value: "Size 10 Object. Therefore, if the labelledObj type of the method parameter is {label: string}, it indicates that the parameter has a label attribute of the string type.

However, this method seems a bit confusing. You can use an interface to define the parameter type of this method.

?

1

2

3

4

5

6

7

8

9

10

Interface LabelledValue {

}

 

Function printLabel (labelledObj: LabelledValue ){

Console. log (labelledObj. label );

}

 

Var myObj = {size: 10, label: "Size 10 Object "};

PrintLabel (myObj );

Optional attributes

In some cases, we can use the optional attribute to define attributes without having to exist.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Interface SquareConfig {

Color? : String;

Width? : Number;

}

 

Function createSquare (config: SquareConfig): {color: string; area: number }{

Var newSquare = {color: "white", area: 100 };

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 passed in the createSquare method for implementing an object of the SquareConfig interface.

Since it is completely dispensable, why should we define it? It is not defined at all. Defining optional attributes has two advantages. 1. If an attribute exists and the type can be constrained, this is critical. 2. You can get a syntax prompt. If you mistakenly write the color in the method body as collor, the compilation fails.

Method Type

In JavaScript, method function is a basic type. In the object-oriented thinking, the implementation of interfaces relies on classes. As a function, can it implement interfaces? The answer is yes.

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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 limits the signature of a method. This method has two string parameters and returns a Boolean value. In the second code, we declare the implementation of this interface.

Note that the compiler only checks whether the type is correct (the parameter type and return value type), so the parameter name can be changed to another one.

?

1

2

3

4

5

6

7

8

9

10

Var mySearch: SearchFunc;

MySearch = function (src: string, sub: string ){

Var result = src. search (sub );

If (result =-1 ){

Return false;

}

Else {

Return true;

}

}

This can also be compiled.

Array type

We have defined the method type in the interface above. How should we define the array type? Very simple.

?

1

2

3

4

5

6

Interface StringArray {

[Index: number]: string;

}

 

Var myArray: StringArray;

MyArray = ["Bob", "Fred"];

MyArray is an array, and the indexer is of the number type, and the element is a string.

In the interface definition, the name of the indexer is generally "index" (of course, you can also change it to another name, but generally the name is "index ). So change

?

1

2

3

4

5

6

Interface StringArray {

[MyIndex: number]: string;

}

 

Var myArray: StringArray;

MyArray = ["Bob", "Fred"];

It is also OK.

Note that the index type can only be number or string.

?

1

2

3

4

5

6

7

Interface Array {

[Index: number]: any;

}

 

Interface Dictionary {

[Index: string]: any;

}

The above two sections can be compiled.

Note that if the interface already belongs to the array type, all other attributes defined in the interface must belong to the element type of the array. For example:

?

1

2

3

4

Interface Dictionary {

[Index: string]: string;

Length: number; // error, the type of 'length' is not a subtype of the indexer

}

The compilation will fail. You need to change the length to the string type.

Class implementation Interface

In general, we are still used to using a class to implement the required interface, rather than directly using the interface as above.

?

1

2

3

4

5

6

7

8

Interface ClockInterface {

CurrentTime: Date;

}

 

Class Clock implements ClockInterface {

CurrentTime: Date;

Constructor (h: number, m: number ){}

}

In TypeScript, the class keyword is used for declaration, which is the same as EcmaScript 6.

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

?

1

2

3

4

5

6

7

8

9

10

11

12

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.

?

1

2

3

Interface ClockInterface {

New (hour: number, minute: number );

}

Then we may write the following naively:

?

1

2

3

4

5

6

7

8

Interface ClockInterface {

New (hour: number, minute: number );

}

 

Class Clock implements ClockInterface {

CurrentTime: Date;

Constructor (h: number, m: number ){}

}

This cannot be done !!! Because the constructor is static, and the class can only implement the instance (instance) part of the interface.

Is the constructor defined in this interface useless? Since TypeScript provides this function, it will certainly not be ineffective. The declared method is special:

?

1

2

3

4

5

6

7

8

9

10

11

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. Here we direct the Clock class to the ClockStatic interface. Note that the newClock variable type is any.

Inheritance Interface

Like a class, interfaces can also be inherited, using the extends keyword.

?

1

2

3

4

5

6

7

8

9

10

11

Interface Shape {

Color: string;

}

 

Interface Square extends Shape {

SideLength: number;

}

 

Var square = <Square> {};

Square. color = "blue ";

Square. sideLength = 10;

Of course, it can also inherit multiple interfaces.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Interface Shape {

Color: string;

}

 

Interface PenStroke {

PenWidth: number;

}

 

Interface Square extends Shape, PenStroke {

SideLength: number;

}

 

Var square = <Square> {};

Square. color = "blue ";

Square. sideLength = 10;

Square. penWidth = 5.0;

It should be noted that, although multiple interfaces can be inherited, if the types of attributes with the same name are different in the inherited interfaces, they cannot be compiled.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

Interface Shape {

Color: string;

Test: number;

}

 

Interface PenStroke {

PenWidth: number;

Test: string;

}

 

Interface Square extends Shape, PenStroke {

SideLength: number;

}

The Code cannot be compiled because the type of the test attribute cannot be determined.

Use the above types at the same time

If you can only use a single type, this interface is too weak. Fortunately, our interfaces are very powerful.

?

1

2

3

4

5

6

7

8

9

10

Interface Counter {

(Start: number): string;

Interval: number;

Reset (): void;

}

 

Var c: Counter;

C (10 );

C. reset ();

C. Integer = 5.0;

In this way, three types are used: method (the interface itself is a method), attribute, and method (the method member is defined ).

The above is all the content of this article. I hope you will like it.

Related Article

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.