TYPESCRIPT Handbook Study notes 4

Source: Internet
Author: User

Overview

This is my note to study typescript. There are 2 reasons to write this note, one to be familiar with the relevant writing, and the other to clarify some of the obscure things. For future development, I believe it will be useful for other people as well.

Learn typescript suggest reading Chinese documents or English documents directly. I am looking at the English document .

TYPESCRIPT Handbook Study notes 3

Class Basic use
class Greeter {    //只读,必须在声明的时候或者constructor里面初始化    readonly greeting: string;    //constructor里面的只读    constructor(readonly message: string) {        this.greeting = message;    }    greet() {        return 'Hello, ' + this.greeting;    }}class Greeter01 extends Greeter {    constructor(message: string = 'everyone') {super(message);}    greet() {        return 'hi, ' + this.greeting;    }}let sam = new Greeter01('world');sam.greet();
Public, private and protected
    1. Public is the default if it is not declared to be public.
    2. Private means only internal access, not quilt class access.
    3. Protected refers to an instance of an internal or subclass that can only be accessed.

Attention:

    1. 2 classes are the same, except for the same members, the private and protected elements must come from the same code.
    2. If the constructor of a class is marked as protected, it means that the class cannot be instantiated, it can only generate subclasses, and then instantiate subclasses.
Access device

Accessors are capable of intercepting and rewriting read-write properties, and if only get is not set, it is considered read-only.

let language = {  log: ['example', 'test'],  set current(name) {    this.log.push(name);  },  get current() {    if (this.log.length === 0) {        return undefined;    } else {        return this.log[this.log.length - 1];    }  }}language.current = 'EN';console.log(language.current);
Static Properties and methods

A static property or method that is preceded by a property or method, is accessed by the instance property or method with the class name.

Abstract class

Abstract classes and interfaces are similar, can only be inherited, cannot be instantiated, and interfaces are different, abstract classes can define methods, which can be inherited.

Abstract classes also have abstract properties, and abstract properties, like interfaces, must be implemented in subclasses.

Class is used as an interface

Good understanding, look at the following code can be.

class Point {    x: number;    y: number;}interface Point3d extends Point {    z: number;}let point3d: Point3d = {x: 1, y: 2, z: 3};
Shorthand form and complete form of function

Because the complete form can be inferred from shorthand form when compiling, it is recommended to use shorthand form.

//简写形式function add(x: number, y: number): number {    return x + y;}let myAdd = function(x: number, y: number): number { return x + y; };//完整形式let myAdd: (x: number, y: number) => number =    function(x: number, y: number): number { return x + y; };
Optional parameters and default parameters
//可选参数function buildName(firstName: string, lastName?: string) {    return firstName + " " + lastName;}//默认参数function buildName(firstName: string, lastName = "Smith") {    return firstName + " " + lastName;}

The function types for the optional and default parameters are the same: (firstName: string, lastName?: string) => string . For ease of writing, the default parameters are better written in the back.

Many parameters can also be deconstructed and expanded, examples are as follows:

function buildName(firstName: string, ...restOfName: string[]) {    return firstName + " " + restOfName.join(" ");}let buildNameFun: (fname: string, ...rest: string[]) => string = buildName;
This

Here's how this works: Understand the function calls and this in JS.

If this error is encountered, it can be resolved by adding this:void or this: class name.

Note that the following is a direct use of the equal sign is an experimental writing, ES6 does not support, only on the ES7 made a proposal. But both typescript and react support the writing.

//用浏览器的审查元素运行,会报错class Handler {    onClickGood = () => { console.log(this); }}

In general, if you want to use the equal sign, we need to write in constructor (note to add this).

//写在constructor里面class Handler {    constructor() {        this.onClickGood = () => { console.log(this); }    }}let myHandler = new Handler();myHandler.onClickGood();
function overloading

Look at the following example, notice that the first 2 is the function overload, and the last is the function declaration. At compile time, will judge each function type, if these 2 are not met, will error.

let suits = ["hearts", "spades", "clubs", "diamonds"];function pickCard(x: {suit: string; card: number; }[]): number;function pickCard(x: number): {suit: string; card: number; };function pickCard(x): any {    // Check to see if we're working with an object/array    // if so, they gave us the deck and we'll pick the card    if (typeof x == "object") {        let pickedCard = Math.floor(Math.random() * x.length);        return pickedCard;    }    // Otherwise just let them pick the card    else if (typeof x == "number") {        let pickedSuit = Math.floor(x / 13);        return { suit: suits[pickedSuit], card: x % 13 };    }}

TYPESCRIPT Handbook Study notes 4

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.