TypeScript entry-interface, typescript entry interface

Source: Internet
Author: User

TypeScript entry-interface, typescript entry interface
Too many rows too many rowsIntroduction

In TypeScript, an interface is used to name these types and define contracts for your code or third-party code.

 

▓ Interface

Example:

    function printLabel(labelledObj: { label: string }) {      console.log(labelledObj.label);    }    let myObj = { size: 10, label: "Size 10 Object" };    printLabel(myObj);

The printLabel function has a parameter that requires this parameter to be an object and has an attribute named "label" of the string type.

Sometimes multiple parameters are passed in, but only the specified parameters are checked.

 

Use the interface to implement the above example:

    interface LabelledValue {      label: string;    }    function printLabel(labelledObj: LabelledValue) {      console.log(labelledObj.label);    }    let myObj = {size: 10, label: "Size 10 Object"};    printLabel(myObj);

Note: The keyword interface is used.

 

Optional attributes

Sometimes the attributes in the interface are not mandatory or optional, so you only need to add one? You can.

    interface SquareConfig {      color?: string;      width?: number;    }    function createSquare(config: SquareConfig): {color: string; area: number} {      let newSquare = {color: "white", area: 100};      if (config.color) {        newSquare.color = config.color;      }      if (config.width) {        newSquare.area = config.width * config.width;      }      return newSquare;    }    let mySquare = createSquare({color: "black"});

In the above Code, config: SquareConfig specifies the function parameter, {color: string; area: numner} specifies the type of the function return value.

Benefits of using optional attributes:

1. Possible attributes can be defined.

2. You can capture errors when accessing non-existent attributes.

 

▓ Read-only attribute

If you want to make a value read-only, you can use readonly if it cannot be modified.

    interface Point {        readonly x: number;        readonly y: number;    }    let p1: Point = { x: 10, y: 20 };    p1.x = 5; // error!

  

TypeScript has the ReadonlyArray <number> type, which is similar to Array <T>, but removes variable methods. Therefore, you can ensure that the Array can no longer be modified after it is created:

    let a: number[] = [1, 2, 3, 4];    let ro: ReadonlyArray<number> = a;    ro[0] = 12; // error!    ro.push(5); // error!    ro.length = 100; // error!    a = ro; // error!

 

Additional attributes are checked.

Let's look at an example:

    interface SquareConfig {        color?: string;        width?: number;    }    function createSquare(config: SquareConfig): { color: string; area: number } {        // ...    }    let mySquare = createSquare({ colour: "red", width: 100 });

At first, we thought this was correct. The interface defines two optional attributes: color and width. The function actually imports the width attribute and the color attribute that is not defined by an interface, but this code reports an error.

The object literal is specially treated and goes throughAdditional property checkWhen they are assigned to variables or passed as parameters. If an object literal contains any attribute not included in the target type, you will get an error.

  

The best solution is to add a string index signature.

    interface SquareConfig {        color?: string;        width?: number;        [propName: string]: any;    }

 

▓ Function Type

Example:

    interface SearchFunc {      (source: string, subString: string): boolean;    }    let mySearch: SearchFunc;        mySearch = function(src, sub) {        let result = src.search(sub);        if (result == -1) {            return false;        }        else {            return true;        }    }

  

Types of indexes that can be indexed

The index type is a [10] Or obj ['a']. The index type has oneIndex SignatureIt describes the object index type and the corresponding index return value type.

    interface StringArray {      [index: number]: string;    }    let myArray: StringArray;    myArray = ["Bob", "Fred"];    let myStr: string = myArray[0];    

 

 

References:

Unveil chapter 2 of Angular2

TypeScript Handbook (Chinese Version)

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.