Take you to understand the 14 basic syntax of Typescript

Posted by erasam on Fri, 03 Dec 2021 19:52:09 +0100

Absrtact: Typescript can be said to be a superset of JavaScript. Many syntax features are added on the basis of JS, so that types can no longer be converted at will, which can greatly reduce errors in the development stage.

This article is shared from Huawei cloud community< Full parsing of Typescript basic syntax >, author: Aurora Borealis night.

1, What is Ts:

First, strong types do not allow arbitrary implicit type conversions, while weak types do. JavaScript is a classic weakly typed language. Typescript can be said to be a superset of JavaScript. Many syntax features are added on the basis of JS, so that types can no longer be converted at will, which can greatly reduce errors in the development stage.

2, Basic syntax:

1. Declare the original data type:

Specify a keyword after a variable to indicate what type it can only be.

string type:

const a: string = 'auroras'

number type:

const b: number = 666 // include NAN Infinity

boolean type:

const c: boolean = true

null type:

const d: null = null

undefined type:

const e: undefined = undefined

symbol type:

const h: symbol = Symbol()

2. Declare Object type:

First, the object type can specify not only objects, but also arrays or functions:

const foo1: object = {};
const foo2: object = [];
const foo3: object = function(){};

If you only want to specify as an object, the object properties must declare the type in advance as follows:

const obj: {name: string,age: number} = {
    name: 'The aurora borealis',
    age:18
}

3.1 declare array type:

You can specify the declaration Array and specify the element type through < >. For example, specify an Array whose declaration elements are numbers:

const arr: Array<number> = [1,2,3]

The second method is as follows. You can also specify an array in which all declaration elements are numbers:

const arr: number[] = [1,2,3]

3.2 declared tuple type:

It is to specify the type of each element in the array in advance and strictly correspond to each other one by one:

const tuple: [number,string,boolean] = [666,'auraros',true]

4. Declare enumeration type:

Declare an enumeration type through the keyword enum, such as:

enum Status {
    pedding = 1,
    resolve = 2,
    reject = '3'
}
//visit
console.log(Status.pedding);

If no value is written at all, the default value is to increment from 0. If the first element is of character type, all values must be defined. If the first element is specified as a number and the subsequent element does not write a value, the value is the result of the increment of the value of the first element by position and size.

5. Function parameters and return types:

Function declaration formula:

Specify the type of parameter passed in from the function and the type of return value. When calling, the number and type of parameters passed in must be the same:

Each parameter type is specified in parentheses, and the type of return value is specified on the right of parentheses.

function fun (name:string,age:number):string{
  return 'sss'
}
fun('auroras',18);

If the incoming parameter is uncertain, you can add a '?' to the parameter Indicates that it is optional:

function fun (name:string,age?:number):string{
  return 'sss'
}
fun('auroras');

Or add a default value to the parameter, which will also become an optional parameter:

function fun (name:string,age:number=666):string{
  return 'sss'
}
fun('auroras');

If the number of parameters is uncertain, it can be represented by extension operator and deconstruction assignment. Of course, it is necessary to pass in the following parameters consistent with the specified type:

function fun (name:string,age:number=666,...res:number[]):string{
  return 'sss'
}
fun('auroras',1,2,3);

Function expression:

const fun2:(name:string,age:number)=>string = function(name:string,age:number){
  return 'sss'
}

I'll elaborate when defining the interface.

6. Any type:

By specifying the any keyword to represent any type, you can assign values of different types as the original js:

let num:any = 1;
num = 'a';
num = true;

7. Type assertion:

Type assertion is to explicitly tell typescript that this variable is of a certain type, which is 100% certain. Do not use typescript. In some cases, you have to infer the type of some undefined or changeable scenes.

You can assert that it is of some type through the as + type:

const res = 1;
const num = res as number;

You can also assert in the form of < type > (not recommended):

const res = 1;
const num = <number>res

8. Basic interface usage:

An interface can be understood as a specification and a contract. You can constrain which members should be in an object and how these members are.

Define a Post interface through the interface. This interface is an object. The rule is that there is a name attribute with the type of string and an age attribute with the type of number.

interface Post {
    name:string;
    age:number
}

Then, for example, if there is a function printPost whose parameter post uses the rules of the post interface defined by us, the data conforming to the rules of the post interface should be passed in when calling this function.

interface Post {
    name:string;
    age:number
}

function printPost(post: Post){
    console.log(post.name);
    console.log(post.age);
}
printPost({name:'asd',age:666})

Of course, some parameters may be optional when passing function parameters, so we can also define optional members for the interface and add a '?' after the attribute Specify optional members:

interface Post {
    name:string;
    age:number;
    sex?:string;
}

const auroras: Post = {
    name:'asd',
    age: 18
}

If a member is modified with readonly, the member property cannot be modified after initialization:

interface Post {
    name:string;
    age:number;
    sex?:string;
    readonly like:string 
}

const auroras: Post = {
    name:'asd',
    age: 18,
    like: 'natrue'
}
auroras.name = 'aaaa';
//Error protection
auroras.like = 'wind';

If you are not sure about the member attribute name, you can declare a dynamic member. Specify the type of member name and member value, such as:

interface Post {
  [prop:string]:string
} 
const auroras: Post = {
    name:'asd',
    like: 'natrue'
}

9. Basic use:

Describe the abstract features of a class of concrete things. ts enhances the syntax of class class in es6.

First, the properties of the class must be declared in advance:

class Person {
    name: string;
    age: number;
    constructor(name:string,age:number){
       this.name = name;
       this.age = age;
    }
    sayHi(msg:string):void {
        console.log(`hi,${msg},i am ${this.name}`);
    }
}

10. Access modifier of class:

private   Modifies a private property that can only be accessed inside a class. public   Modify public properties (default), and external can also access:

class Person {
  public  name: string;
  private  age: number;
  constructor(name:string,age:number){
       this.name = name;
       this.age = age;
    }
  sayHi(msg:string):void {
        console.log(`hi,${msg},i am ${this.name}`);
        console.log(this.age);
    }
}

const jack = new Person('jack',20);
//Person Class public properties can be accessed
console.log(jack.name);
//Person Class private properties are not accessible
console.log(jack.age);

Protected is modified to be protected and not accessible externally. But with   private   The difference is that if the inherited subclass is accessible.

class Person {
  public  name: string;
  private  age: number;
  // protected
  protected gender: boolean;
    constructor(name:string,age:number){
       this.name = name;
       this.age = age;
       this.gender = true;
    }
    sayHi(msg:string):void {
        console.log(`hi,${msg},i am ${this.name}`);
        console.log(this.age);
    }
}

class children extends Person{ 
    constructor(name:string,age:number){
        super(name,age,);
        //Can access
        console.log(this.gender);
    }
}

11. Class read-only attribute:

Set properties   readonly   It is a read-only attribute, which cannot be modified after initialization.

class Person {
  public  name: string;
  private  age: number;
  // readonly
  protected readonly gender: boolean;
    constructor(name:string,age:number){
       this.name = name;
       this.age = age;
       this.gender = true;
    }
    sayHi(msg:string):void {
        console.log(`hi,${msg},i am ${this.name}`);
        console.log(this.age);
    }
}

12. Class and interface:

There are some common features between some classes, which can be abstracted into interfaces.

For example, although the Person class and the Animal class are different, both humans and animals can eat and walk. These common features can be defined by the interface. The last feature defines an interface.

//Eat interface
interface Eat {
    eat(food:string):void
}
//Travel interface
interface Run {
    run(behavior:string):void
}
//people
class People implements Eat,Run {
    eat(food:string){
       console.log(`Eat at the table ${food}`);
    }
    run(behavior:string){
       console.log(`stand ${behavior}`);
    }
}
//animal
class Animal implements Eat,Run {
    eat(food:string){
       console.log(`Eat on the ground ${food}`);
    }
    run(behavior:string){
       console.log(`Crawling ${behavior}`);
    }
}

13. Abstract class:

Constraint subclasses must have some members, which is a bit similar to interfaces. The difference is that abstract classes can contain some concrete implementations. For example, animals should be an abstract class. Its subclasses include cats, dogs, pandas, etc. They are all animals and have some common characteristics. After a class is defined as an abstract class, it can no longer be a new instance, but can only be inherited by its subclasses.

Where abstract   Define an abstract class. An abstract method is defined in the class, and the subclass must implement the abstract method.

abstract class Animal  {
    eat(food:string){
       console.log(`Eat on the ground ${food}`);
    }
    abstract run (behavior:string):void
}
//cat
class Dog extends Animal{
    run(behavior:string):void{
        console.log(behavior);
    }
}
const d1 = new Dog();
d1.eat('bone')
d1.run('Four legged crawling') 
//rabbit
class rabbit extends Animal{
    run(behavior:string):void{
        console.log(behavior);
    }
}
const r1 = new rabbit();
d1.eat('radish')
d1.run('Bouncing') 

14. Generics:

A generic type is one that does not specify a specific type when defining a function, interface or class, and does not specify a specific type until it is used. Reuse code to a great extent.

For example, there is an identity function, which will return any value passed in, and the type passed in should be the same as the type returned. If you pass in a number without generics, this function may be as follows:

 function identity(arg:number):number{
     return arg
 }

If a string is passed in, the function may be as follows:

 function identity(arg:string):string{
     return arg
 }

This is too troublesome, so you can use generics. Generally, the capital T represents generics. It can be applied to multiple types, and the incoming type is the same as the return type.

 function identity<T>(arg:T):T{
     return arg
 }

 

Click focus to learn about Huawei cloud's new technologies for the first time~

Topics: Javascript TypeScript array