Today we’ll take a quick look at TypeScript to get you started

Summary of TypeScript

  • A superset of javascript
  • Any javascript runtime environment is supported
  • The function is more powerful, and the ecology is more sound and perfect

disadvantages

  • The language itself adds a lot of concepts
  • Small projects, early projects, add some cost

Quick learning

- yarn add typescript  --dev
- yarn tsc hello.ts    //= A js file with the same name will be generated
- tsc hello.ts     // Run TSC file
Copy the code

The configuration file

- yarn tsc --init  // Initialize the configuration file
- target  // Set the typescript standard ES2015 ES2016 to use after compilation
- module  // Import/export operations such as CommonJS AMD UMD
- outDir // Compressed output directory
- rootDir // The source directory
- sourceMap  // Whether to enable source mapping
- strict  // Whether to enable strict mode
-
Copy the code

The original type

Empty \ is allowed by default

  • string
  • number
  • boolean
  • void
  • null
  • undefined
  • symbol

Standard library declaration

- Declarations corresponding to built-in objects - Smybol and when using strict modeconsoleError - Resolution1: Set targer in tsconfig.json file to ES2015 - workaround2: Added to the configuration file"lib": ['ES2015'.'DOM'] - The built-in object must reference the corresponding built-in libraryCopy the code

TypeScript Chinese error messages

yarn tsc --locale zh-CN   // Sets the command line error message to ChineseFind the typescript locale file in Settings and set it to zh-cn// This allows you to set the error in the code to Chinese but is not recommended for adverse error search
Copy the code

Scope problem

An error occurs when a variable is defined globally and another file defines the same variable

1.Using closures (function (){
   const a = 124}) ()2.throughexportThe export is thus a member of the forming module scopeCopy the code

The object type

Object represents a non-primitive type, that is, a type other than number, string, Boolean, symbol, NULL, or undefined.

Use the object type to better represent apis like Object.create. Such as:

declare function create(o: object | null) :void;

create({ prop: 0 }); // OK
create(null); // OK

create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error
Copy the code

An array type

Three ways of defining it

const arr1: Array<number> = [1.2.3]
const arr2:number[] = [12.3]

function sun(. args:number[]){
    return args.reduce((prev,current) = >prev+current,0)}Copy the code

A tuple type

export {}  // Make sure there are no member conflicts in other instances
const tuple:[number,string] = [18.'dd']

const [age,name] = tuple
Copy the code

Enumerated type

enmu

enum PostStatus {
    success = 1,
    error = 2,
    warning =3
}

// If the value is not set, 1 is accumulated from 0 by default
enum PostStatus {
    success ,   / / 0
    error ,     / / 1
    warning     / / 2
}

// If the first value is set, 1 is incremented from the first value
enum PostStatus {
    success = 3 ,
    error ,    / / 4
    warning    / / 5
}

// Enumeration types invade our runtime code
// The result is a bidirectional key-value pair that can either pass the key by value or get the value by key


// Since we don't usually use values to get keys, we can just prefix enum with a const keyword
const enum PostStatus {
    success = 1,
    error = 2,
    warning =3
}
Copy the code

Function types

export {}  // Make sure there are no member conflicts with other examples

function fn(a:string,b:string) :string {
    return a+b
}

// The parameter is fixed and cannot be greater than the current number
// We can use the REST operator of ES6 if we need any arguments
function fn(a:string, b:string, ... rest:string[]) :string {
    return a+b
}

fn("hello")
fn('hello'.'world')
fn('hello'.'world'.'1')
Copy the code

Any type

Sometimes we want to specify a type for variables whose type is not known at programming time. These values may come from dynamic content, such as user input or third-party code libraries. In this case, we don’t want the type checker to check these values and just pass them through compile-time checks. Then we can mark these variables with type any: \

function add(a){
    return JSON.stringify(a)
}
// So our argument a defaults to any type

add(1)
add("hhh")
add([1.2.3])
// No errors will be reported at compile time
let notSure: any = 4;
// It is usually better to add any after the parameter by default
Copy the code

Void

In a way, void is like the opposite of any; it means there is no type at all. When a function returns no value, you usually see the return type void:

function warnUser() :void {
    console.log("This is my warning message");
}
Copy the code

Declaring a void variable doesn’t do much good, because you can only assign undefined and null to it:

let unusable: void = undefined;
Copy the code

Implicit type inference

If we don’t specify a type, our typescript does an implicit type inference for us

/ / such as
const a= 12; At this point our a is implicitly assigned to a numberCopy the code

Types of assertions

\

Sometimes you’ll find that you know more about a value than TypeScript does. Usually this happens when you clearly know that an entity has a more exact type than its existing type.

Type assertions are a way of telling the compiler, “Trust me, I know what I’m doing.” Type assertion is like conversion in other languages, but without special data checking and deconstruction. It has no run-time impact, only at compile time. TypeScript assumes that you, the programmer, have done the necessary checks.

Type assertions come in two forms. The first is the Angle bracket syntax:

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;
Copy the code

The other is the as syntax:

let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;
Copy the code

The two forms are equivalent. Which to use is mostly a matter of personal preference; However, when you use JSX in TypeScript, only AS syntax assertions are allowed.

export {}  // Make sure there are no conflicts with other examples

const nums = [20.30.40];

// Normally a numeric type is returned but undefined is returned if it is not found
const res = nums.find(i= > i>0)
// So we can use type assertion when we clearly know that the output is of a certain type
const num1 = res as number  Method 1 uses as followed by the type
const num2 = <number>res    // Method 2 is preceded by 
      
        but JSX syntax conflicts so method 1 is recommended
      
Copy the code

interface

For an object to implement an interface, all members of the object constraint must have normal, optional, dynamic, and read-only \

export {}  // Make sure there are no conflicts with other examples


// Use the interface keyword to define the interface
interface Post{
    title:string
    status:number subtitle? :string// Optional member
    readonly name:string   // The read-only member can only be read after being set
}

function printPost (post:Post){
    console.log(post.title)
    console.log(post.status)
    console.log(post.name)
}

printPost({
    title:"success".status:200.name:"dali"
})

interface Cache {
    [prop:string]:string  // After this is defined, you can add the property name and value as you like, but the type must be string
}

const cache:Cache ={}

cache.name = "dali"
cache.hobby = 'study'
Copy the code

class

An abstract member used to describe a class of concrete objects must be annotated with \ before it can be used

export {}  // Make sure there are no conflicts with other examples

class Person{
    // Need to be marked here
    name:string
    age:number

    constructor(name:string,age:number){
        this.name = name
        this.age = age
    }
}
Copy the code

Access modifier

If you declare a property private, that property belongs only to that class. Access to this property can only be done in this class. Is not accessible in the object of either a subclass or an implementation of the class. This property can be used indirectly in subclasses by calling methods that use this property. Protected Protected objects. Because a class can be a lot of objects. Objects should not have access to or modify the same properties that these objects should have in common. For protected declared properties, you can access them in subclasses. Cannot be accessed in the implementation object. Constructor for protected declarations. This method can only be called in a j inherited subclass and not directly when the object is created. That is, the class can only be inherited and not implemented. \

export {}  // Make sure there are no conflicts with other examples

class Person{
    // Need to be marked here
    public name:string          // Can be accessed
    private age:number        // Can only be accessed inside the class
    protected readonly gender:boolean   // Private in class and in subclass access to readonly Read-only not allowed to change


    constructor(name:string,age:number,gender:boolean){
        this.name = name
        this.age = age
        this.gender = true}}Copy the code

Classes and interfaces

Generally, an interface abstracts a class \

export {}  // Make sure there are no conflicts with other examples

interface Eat {
    eat (food:string): void
}

interface Run {
    run (distance:number): void
}

class Person implements Eat.Run{
    eat (food:string):void{
        console.log('Eating with chopsticks:${food}`)
    }
    run (distance: number){
        console.log('Walking in shoes:${distance}`)}}class Animal implements Eat.Run{
    eat (food:string):void{
        console.log('Eat straight:${food}`)
    }
    run (distance: number){
        console.log('Barefoot walking:${distance}`)}}Copy the code

An abstract class

Unlike interfaces, which can contain some concrete implementation but can only be an abstraction of a member, there are no concrete implementation methods

The generic

Turn an undefined type into an argument and then pass the argument \ as we use it

export {}  

// Add 
      
        after the method name and after the required incoming type
      
function creatArray<T> (length:number, value:T) :T[] {
        const arr = Array<T>(length).fill(value)
        return arr
}

// Write the type into this when creating <>
// This is called generics
// This approach makes creation more flexible
const res = creatArray<string>(3.'Tmi')   //['Tmi','Tmi','Tmi']
Copy the code

Type declaration

Declare function fn(a:string):string; declare function FN (a:string):string; We just need to install the corresponding type declaration module \

We only introduce the simple use here if you want to know more detailed suggestions below the official website link

The base type, TypeScript, Chinese TypeScript – a superset of JavaScript, www.tslang.cn/docs/handbook/basic-types.html

Good to see the little partners start to practice it ~

Like remember to like! Pay close attention to yo ~