Share 13 basic syntax of Typescript

Share 13 basic syntax of Typescript

1. What is Ts

First, strong typing does not allow arbitrary implicit type conversions, while weak typing allows them. JavaScript is a classic weakly typed language. Typescript can be said to be a superset of JavaScript . It adds many syntax features based on JS, so that types can no longer be converted at will, which can greatly reduce errors in the development phase.

2. Basic Grammar

1. Declare primitive data types

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

string type:

const a: string = 'auroras'


Number type:

const b: number = 666 // including 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 of all, the object type can not only specify objects, but also arrays or functions:

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


If you only want to specify it as an object, as follows, the type of the object attributes must be declared in advance:

const obj: {name: string, age: number} = {
    name: 'Northern Lights',
    age:18
}


2.1 Declaring array types

You can declare an Array and specify the element type through <>, for example, to declare an array where all elements are numbers:

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


The second way is as follows, which also specifies that the array elements are all numbers:

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


2.2 Declaring Tuple Types

It is to specify the type of each element in the array in advance, strictly one-to-one correspondence:

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


3. Declare enumeration type

An enumeration type is declared using the enum keyword, such as:

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


If no value is written, the default value starts from 0 and increases. If the first element is of character type, the value must be fully defined. If the first element is specified as a number and no value is written for the following elements, the value is the result of increasing the value of the first element by position.

4. Function parameters and return types

Function declaration:

Specify the function's incoming parameter type and return value type. The number and type of parameters passed in must be the same when calling:

The type of each parameter is specified in the brackets, and the type of the return value is specified on the right side of the brackets.

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


If you are not sure whether to pass the parameter, you can add a '? ' 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 optional:

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


If the number of parameters is uncertain, you can use the spread operator plus deconstruction assignment to represent it, of course, you must pass in the same type as the specified one:

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'
}


We will explain this in detail when defining the interface.

5. Any type

By specifying the any keyword to represent any type, just like the original js, you can assign values ​​of different types at will:

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


6. Type Assertions

Type assertion is to explicitly tell typescript that this variable is of a certain type, 100% certain. Without typescript you have to infer the type of some undefined or changeable scenarios in some cases.

You can use as + type to assert that it is of a certain type:

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


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

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


7. Basic use of the interface

An interface can be understood as a specification, a contract. You can constrain which members an object should have and what these members are like.

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

interface Post {
    name: string;
    age:number
}


For example, if there is a function printPost , its parameter post uses the rules of the Post interface we defined. When calling this function, you need to pass in data that conforms to the Post interface rules.

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 parameters to a function, so we can also define optional members for the interface by adding a '?' after the attribute. 'Specify optional members:

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

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


If you modify a member with readonly, then 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';
//Guaranteed error auroras.like = 'wind';


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

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


8. Basic use of classes

Describes the abstract characteristics of a specific class of things. ts enhances the class -related syntax in es6 .

First, the attributes of the class must be declared before use:

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}`);
    }
}


9. Class access modifiers

private modifies private properties and can only be accessed within the class. public modifies public attributes (default),

External access is also available:

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 cannot be accessed console.log(jack.age);
protected modifies it as protected and cannot be accessed from outside. But the difference from private is that inherited subclasses can access it.

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);
    }
}

10. Class read-only properties

Setting readonly to a property makes it a read-only property, and the property 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);
    }
}


11. Classes and Interfaces

Some classes have some common features, which can be abstracted into interfaces.

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

//Eat interface interface Eat {
    eat(food:string):void
}
//Run interface interface Run {
    run(behavior:string):void
}
//class People implements Eat,Run {
    eat(food: string){
       console.log(`Eat ${food} on the table`);
    }
    run(behavior:string){
       console.log(`Standing ${behavior}`);
    }
}
//Animal class Animal implements Eat,Run {
    eat(food: string){
       console.log(`eat ${food} on the ground`);
    }
    run(behavior:string){
       console.log(`crawling ${behavior}`);
    }
}


12. Abstract Class

Constraining subclasses to have certain members is somewhat similar to an interface, except that abstract classes can contain some specific implementations. For example, the animal class should be an abstract class, and its subclasses include cats, dogs, pandas, etc. They are all animals and have some common characteristics. After defining a class as an abstract class, new instances can no longer be created and it can only be inherited by its subclasses.

Abstract defines an abstract class, and abstract is used to define an abstract method in the class. Subclasses must implement the abstract method.

abstract class Animal {
    eat(food: string){
       console.log(`eat ${food} on the ground`);
    }
    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('crawling on four legs') 
//rabbit class rabbit extends Animal {
    run(behavior:string):void{
        console.log(behavior);
    }
}
const r1 = new rabbit();
d1.eat('radish')
d1.run('jumping') 


13. Generics

Generics means that the specific type is not specified when defining a function, interface, or class, and the specific type is specified when it is used. Reuse code to a great extent.

For example, there is an identity function, which returns any value passed into it, and the type passed in should be the same as the type returned. If you pass in a number without generics,

This function might look like this:

 function identity(arg:number):number{
     return arg
 }
If passed a string, the function might look like this:

 function identity(arg:string):string{
     return arg
 }
This is too troublesome, so you can use generics, which are generally represented by capital T. Generics can be applied to multiple types, and the incoming type and the return type are the same.

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

This is the end of this article about sharing the 14 basic syntax of Typescript. For more information about the 14 basic syntax of Typescript, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Introduction to TypeScript basic types
  • TypeScript enumeration basics and examples
  • TypeScript Basics Tutorial: Triple Slash Instructions
  • Detailed explanation of TypeScript's basic types

<<:  Sample code for easily implementing page layout using flex layout

>>:  Detailed explanation of the basic usage of the img image tag in HTML/XHTML

Recommend

How to make if judgment in js as smooth as silk

Table of contents Preface Code Implementation Ide...

Native js to achieve simple carousel effect

This article shares the specific code of js to ac...

Let's talk in depth about the principle and implementation of new in JS

Table of contents definition Constructor bodies a...

Solve the problem of margin merging

1. Merge the margins of sibling elements The effe...

Summary of MySQL character sets

Table of contents Character Set Comparison Rules ...

MySQL series: redo log, undo log and binlog detailed explanation

Implementation of transactions The redo log ensur...

An article to understand the advanced features of K8S

Table of contents K8S Advanced Features Advanced ...

Quick understanding of Vue routing navigation guard

Table of contents 1. Global Guard 1. Global front...

Detailed usage of js array forEach instance

1. forEach() is similar to map(). It also applies...

CSS pseudo-class: empty makes me shine (example code)

Anyone who has read my articles recently knows th...

Detailed explanation of Strict mode in JavaScript

Table of contents Introduction Using Strict mode ...

How to add Tomcat Server configuration to Eclipse

1. Window -> preferences to open the eclipse p...

MySQL5.7 parallel replication principle and implementation

Anyone who has a little knowledge of data operati...

IDEA2020.1.2 Detailed tutorial on creating a web project and configuring Tomcat

This article is an integrated article on how to c...