The only way to explore the typescript ----- Interface (interface)

TypeScript define the interface
familiar with the programming language students know the importance of the interface (interface) is self-evident. Many are content to use interface. The interface is similar to typescrip java, but also increased the more flexible interface types, including properties, functions, and the like can be indexed, to the operation performed typescript better understanding, the interface must be exposed to. Today I will share with you is, how to use the interface.

I. Why use interfaces
1.1 JavaScript problems.
We define a function in JavaScript, a string obtain a user name and age for:
const getUserInfo = function (the User) {
return name: ${user.name}, age: ${user.age}
}
correct call should be the following method way:
getUserInfo ({name: "coderwhy", Age: 18})
but when the project is large, or when people developed the wrong call method will be:
// bad call
getUserInfo () // Uncaught TypeError: can not Property Read 'name' of undefined
the console.log (getUserInfo ({name: "coderwhy"})) // name: coderwhy, Age: undefined
getUserInfo ({name: "codewhy", height: 1.88}) // name: coderwhy , age: undefined
because JavaScript is weakly typed language, so we will not have any incoming code to detect, but indeed there will be many similar security risks before the javaScript in.
How to avoid this problem?
 typescript course use the code to reconstruct
1.2 TypeScript a refactoring.
We can use the above code of typescript to improve:
const getUserInfo = (User: {name: String, Age: Number}): String => {
return name: ${user.name} age: ${user.age};
};
correct call is in the following manner:
getUserInfo ({name: "coderwhy", Age: 18 is});
If the call who appeared the wrong call, then TypeScript will give direct error message:
// bad call
getUserInfo (); // error message: an argument for 'the User' WAS not Provided.
getUserInfo ({name: "coderwhy" }); // error message: Property 'Age' Missing in IS type '{name: String;}'
getUserInfo ({name: "coderwhy", height: 1.88}); // error message: type mismatch
this does prevent false calls occur, but when we defined functions, types and functions of the type parameters are very long, very difficult to read the code.
So, we can use the interface to reconstruct the code again.
1.3.
TypeScript code refactoring two now we use the interface to reconstruct the type of user.
Reconstruction of a Interface: parameter type using an Interface Definition
We define a IUser Interface:
// define an interface
interface IUser {
name: String;
Age: Number The;
}
Next we look at how to write function:
const getUserInfo = (the User: IUser): String => {
return name: ${user.name}, age: ${user.age};
};

// correct calling
getUserInfo ({name: "coderwhy" , age: 18});

// wrong call, the other is the same
getUserInfo ();
Interface reconstruction II: the type of function to use good interface definition (more about this later defined interface functions)
We define two interfaces:
 define a second interface warnings, we ignore it, if its purpose is only one way a function interface, it may be used to define the type
type IUserInfoFunc = (User: IUser) => String;
interface IUser {
name: String;
Age: Number;
}

{IUserInfoFunc interface
(User: IUser): String;
}
Then we call to define the functions and function can be:
const getUserInfo: IUserInfoFunc = (User) => {
return name: ${user.name}, age: ${user.age};
};

// correct calling
getUserInfo ({name: "coderwhy" , age: 18});

// wrong call
getUserInfo ();
. Two interfaces basic use
. 2.1 interfaces defined way
and a lot of other similar language, TypeScript interfaces are defined using the interface keyword to define:
interface IPerson {
name: String;
}
you will find me in front of the interface plus an I, which is tslint requirements, otherwise it will report a warning
 Do not add the prefix is based on the company's norms and personal habits
interface name must start with a capitalized I
of course we can close in tslint in it is out: Add the following rule in the rules in the
"interface-name": [to true, "Never-prefix"]
. 2.2 defined interface methods
defined interface only can have attributes, the method may have:
interface {the Person
name: String ;
RUN (): void;
EAT (): void;
}
if we have an object that the interface type, it must contain the corresponding attributes and methods:
const P: the Person = {
name: "Why",
RUN () {
Console .log ( "running");
},
EAT () {
the console.log ( "eating");
},
};
. 2.3 optional attributes defined
by default a variable (object) corresponding to the type of the interface, then the variable (object) must all properties and methods implemented interface.
However, the development in order to make the interface more flexible, some of the attributes we may want to design an optional (want to achieve can be achieved, do not want to realize it does not matter), this time we can use the optional attributes (later explain in detail the function of time, You'll soon learn function with optional parameters):
interface {the Person
name: String;
Age ?: Number the;
RUN (): void;
EAT (): void;
Study ():? void;
}
the above code, we increasing the age properties and study methods, both of which are optional:
 If the optional attribute no value, then the acquired value is undefined;
 for an alternative method, it must first judge, then call, otherwise it will error ;
const P: = {the Person
name: "Why",
RUN () {
the console.log ( "running");
},
EAT () {
the console.log ( "eating");
},
};

console.log (p.age); // undefined
p.study (); // can not call might be "undefined" object.
Correct calling follows:
IF (p.study) {
p.study ();
}
. 2.4 read-only property defined
by default, the interface defined in the readable and writable attribute:
the console.log (p.name);
p.name = "chuanfeng";
if a property, we just want to define value can not be modified after the time defined, you can add a keyword in front of the property: Readonly
interface the Person {
Readonly name: String;
?: Number the Age;
RUN (): void;
EAT (): void;
Study (): void;?
}
when I add readonly in front of the name, assignment error will be:
console.log (p.name);
p.name = "chuanfeng"; // can not assign to ' name' because it is a read-only property.
three advanced use interface.
3.1 function type definition
interfaces can be defined not only ordinary object types, may be function type definition
// function type definition
interface SumFunc {
(num1: number, num2: number): number;
}

// define specific function
const SUM: = SumFunc (num1, num2) => {
return num1 num2 +;
};

// call the function
console.log (sum (20, 30) );
but above the interface is only one function, TypeScript will give us a suggestion, you can use the type to define a type of function:
type SumFunc = (num1: Number The, num2: number) => number;
for more user type, we specifically explain later, temporarily absent from discussions in the interface.
3.2 can be defined index type
type and using the interface described functions similar, we can also use the interface to be described indexable type
 example, a variable may be such access: a [3], a [ "name"]
indexable type having a index signature, which describes the type of object index, as well as the corresponding index return type.
// definition of indexable type interface
interface RoleMap {

}

// assignment specific values
// assignment mode a:
const roleMap1: rolemap = {
0: "student",
1: "Instructor",
2: "teacher",
};

// Assignment way: because the array itself is an index value
const roleMap2 = [ "Luban seven", "Luna", "Bai"];

// Remove the corresponding value
console.log (roleMap1 [0]); // student
console.log (roleMap2 [1]); // Luna
above case, our index is a digital signature type, TypeScript supports two index signature: strings and numbers.
We define a string of index types:
interface {rolemap

}

rolemap const: = {rolemap
AAA: "Luban VII"
BBB: "Luna"
CCC: "Bai"
};

the console.log (roleMap.aaa);
the console.log (rolemap [ "AAA"]); // WARNING: not recommended to take
can use two types of indexes simultaneously, but the number of the index value must be a return string index return value type subtype:
 this is because when a number is indexed, JavaScript converts it into a string and then to the index object.
{the Person class
Private name: String = "";
}

class Student extends Person {
private sno: number = 0;
}

// The following code error
interface IndexSubject {

}
Code error message follows:
numeric index type "Person" is not assigned to a string index type "Student".
Modified as follows code on:
interface IndexSubject {

}
The following code is also given:
Type letter index results obtained, it must be Person type or subtype
interface IndexSubject {

Letter: String;
}
3.3 implementation of the interface.

Note: In this section and the next section, we will write some classes, but there is no detailed study grammar class (although TS class and very similar for ES6).
We know how we can first class definitions, interfaces and how to cooperate to use some of the details I have a special article to resolve the use of the class.
"
Interface specification except after the definition of a certain type, you can also other programming languages, allowing a class to implement an interface, then this class must explicitly to have this interface attributes and implement its methods:
 the code below warning will be about modifiers, ignore, explained later in detail
// define a physical interface to
interface the entity {
title: String;
log (): void;
}

// implement such an interface
class the implements the Entity {Post
title: String;

constructor(title: string) {
this.title = title;
}

log (): void {
console.log (this.title);
}
}
Question: I defined an interface, but I inherited this interface in the implementation but also to write the interface, then I might as well directly in this class write implementation it is more convenient, but also eliminates the need to define interfaces? This is a beginner often have doubts about the place.
From the way of thinking, Why do we need an interface?

We proceed from the understanding of life Interface


For example, you go to Sanya / Hangzhou tour, playing after a morning hungry, you are looking ahead, pay attention to what? Hotel !!


You may not too concerned about what the name of this restaurant called, but you know just behind the hotel word, it means that this place must have realized the hotel - do all kinds of food for you to eat;


interfaces like hotel / Hospitality Affiliated word these terms added later, when we see these words, it will know that they have a subsidiary function

from the code design, the interface Why?
 in code design, the interface is a specification;
 interfaces are typically used for some defined specification, you must abide by similar agreements, and some language directly called protocol;
 standing on procedural point of view only provides the interface properties and methods class that must be provided to separate the specification and implementation, and enhance the system the scalability and maintainability;
of course, for the first time people contactless interface, it is still difficult to understand the benefits of the actual code design, this Gradually began to feel, do not be impatient.
3.3. Inherited interface
And similar to a class (we'll detail later knowledge learning class), the interface can also inherit interface to provide reusability:
 Note: inheritance extends keyword
interface Barkable {
Barking (): void;
}

interface Shakable {
shaking(): void;
}

Petable the extends Barkable interface, Shakable {
eating (): void;
}
Interface Petable inherited from Barkable and Shakable, In addition, we found that an interface can inherit from multiple interfaces at the same time
if we have a class that implements Petable interface, not only need to implement Petable the method, the method Petable inherited from the interface also need to implement:
 Note: implement the interface using the implements keyword
class Dog implements Petable {
Barking (): void {
console.log ( "bark");
}

shaking (): void {
the console.log ( "wag its tail");
}

eating (): void {
the console.log ( "eat bones");
}
}

If you feel that the content would be limited to this interface, it may be wrong, but also in combination with other interfaces while the use of knowledge, which necessarily involves repeated practice you, if you want to improve your programming skills, that it concerns me, I will release you more exciting tutorials to help you break through the bottleneck, self-improvement.

Guess you like

Origin blog.51cto.com/13007966/2452442