TypeScript really fragrant Series - Interface

Foreword

Content TypeScript really fragrant series of reference Chinese documents , but an example of the basic text of the document will not repeat the example, for some places will be in-depth study. In addition, the results of this paper are some examples of errors in the code is not compiled into JavaScript get. If you want to actually look at TypeScript compiled into JavaScript code, you can access TypeScript of online compilation addresses , hands-on, more impressive.

concept

Is one of the core principles TypeScript values ​​has a structure type checking. It is sometimes called "duck-type resolution method" or "structural subtyping." In TypeScript, the role of the interface is named and your code or third-party code is defined for these types of contracts. It can be said that the emergence interface, allows us to detect and avoid many of the problems and improve our development efficiency in development.

Interface base

In object-oriented programming, a definition of the interface specification, which defines the operation and behavior specifications. As in the following example:

interface IDo {
    work:string;
    time:number;
}
interface IMan {
    age:number;
    name:string;
    do:Do;
}

let james: IMan = {
    name: 'james',
    age: 35,
    do: {
        work: 'player',
        time: 2020
    }
}
james.name; //"james"
james.do.work; //"player"

If we type name written in james number 12, that is number type, or did not write age. Then an error message will appear.

Optional attributes

In our development, interface attributes sometimes not all necessary, in the presence of some conditions, under certain conditions and does not exist.

interface IMan {
    age?:number;
    name:string;
}
let james: IMan = {
    name:"james"
}

Read-only attribute

Some object properties whose value can only be modified when the object just created.

interface IMan {
    age:number;
    readonly name:string;
}
let james: IMan = {
    name:"james",
    age:35
}
james.name = "mike"; // error: Cannot assign to 'name' because it is a read-only property.

Additional property inspector

When we can determine an object may have some additional property as a special-purpose use, the best way is to add a string index signature.

interface IMan {
    age:number;
    readonly name:string;
    [propName: string]: any;
}
let james: IMan = {
    name:"james",
    age: 35,
    work:"player"
}

Function Type

Functions are objects, like we can indicate the type of function with the interface.

interface IFunc {
    (x: string, y: string): string;
}
let func: IFunc = function(x: string, y: string){
    return x + y;
}
func("1", "!"); // "1!"

For the function type of type checking, the parameter name of the function does not need to match the name of the interface defined in.

interface IFunc {
    (x: string, y: string): string;
}
let func: IFunc = function(a: string, b: string){
    return a + b;
}
func("1", "!"); // "1!"

Indexable types

It can be used to constrain the arrays and objects.

interface IMan {
    [index:number]:string
}
//数组
let man1: IMan;
man1 = ["james", "wade", "bosh"];
//对象
let man2: Man;
man2 = {1:"haha", 2:"666"};
console.log(man1); //["james", "wade", "bosh"]
console.log(man2); //{1: "haha", 2: "666"}

Class Type

TypeScript interfaces can also be used to explicitly force a class to meet certain requirements, you can use implements to achieve.

interface IMan {
    name:string;
    play(val:string):void;
}

class IFootballer implements IMan {
    name:string
    constructor(name:string){
        this.name = name
    }
    play(val:string){
        console.log(this.name + '踢'+ val)
    }
}

class IBasketballer implements IMan {
    name: string
    constructor(name:string){
        this.name = name
    }
    play(val:string){
        console.log(this.name + '打'+ val)
    }
}
var a = new Footballer('武磊')
a.play("足球") //武磊踢足球

var b = new Basketballer ('姚明')
b.play("篮球") //姚明打篮球

Interface inheritance

And our classes, between the interface can inherit from each other.
i

nterface IMan {
    name: string;
}
interface IPlayer extends IMan {
    types:string
}

class IFootballer implements IPlayer {
    name: string;
    types: string;
    constructor(name:string, types:string){
        this.name = name;
        this.types = types
    }
    play(){
        console.log(this.name+ "是" + this.types)
    }
}

let a = new Footballer("c罗", "足球运动员");
a.play(); //c罗是足球运动员

An interface can inherit multiple interfaces, separated by commas.

interface IMan {
    name: string;
}
interface ICity {
    city:string;
}
interface IPlayer extends IMan,ICity {
    types:string
}

Mixed types
we can make an object at the same time with a variety of types.

interface ICounter {
    (start: number): string;
    interval: number;
    reset(): void;
}

function getCounter(): ICounter {
    let counter = <ICounter>function (start: number) { };
    counter.interval = 123;
    counter.reset = function () { };
    return counter;
}

let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;

Interface inheritance class

When a class inherits the interface type, it inherits the members of the class but does not include its implementation. Like interface declares members of all classes exist, but does not provide the same realization. Interface will also inherit the private and protected members of the class. This means that when you create an interface inherited when a class has private or protected members of this interface can be implemented by this class or sub-class (implement).
When we have a huge inheritance structure when this is useful, but to point out that our code only work when they have a specific sub-class attribute. In addition to this subclass held to the following class has nothing to do with the base class.

class Control {
    private state: any;
}

interface ISelectableControl extends IControl {
    select(): void;
}

class Button extends Control implements ISelectableControl {
    select() { }
}

class TextBox extends Control {
    select() { }
}

// 错误:“Image”类型缺少“state”属性。
class Image implements ISelectableControl {
    select() { }
}
//error
class Location {

}

reference

https://github.com/zhongsp/TypeScript

At last

In some places the text may be added some of their own understanding, if not inaccurate or wrong place, welcome that -
I wish you all a Happy New Year, Family Fu-!
Front-line health care workers want to stay healthy, as soon as possible to defeat the virus!
I hope you are perfectly healthy!

Released four original articles · won praise 4 · views 92

Guess you like

Origin blog.csdn.net/qq_42002487/article/details/104079434