What is TypeScript?

TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript, on which TypeScript adds optional static typing and class-based object-oriented programming.

TypeScript is essentially an enhanced version of JavaScript, but is eventually compiled into JavaScript at runtime. The main goal of TypeScript is to make programmers more creative and productive. It will greatly enhance the development and debugging of JavaScript writing applications, addressing JavaScript’s “pain points” : weak typing and lack of namespaces make it difficult to modularize large applications.

It also provides some syntax candy to help you practice object-oriented programming more easily. Another great benefit of strong typing is intelligent hints, such as knowing what properties and methods the current variable has.

Traditionally, the input and output parameters are noted in the comments, and the editor does not intelligently indicate when writing a business, such as:

After joining TypeScript:What if I deliberately write variables that are not strongly typed as defined:

TypeScript grammar


The parameter types

The types of the parameters in the Typescript are Boolean/number/string array/tuple enum/any/(null, and undefined)/void/never.


Type String

A text that holds a string of type declared string. As you can see, type declarations can be lowercase or uppercase.

let name: string = 'sun'let name2: string = 'jun'Copy the code


Boolen type

Boolean is the value of true or false

let isBool1: boolean = falseCopy the code


The Number type

let number: number = 10Copy the code


Array type

An Array is of Array type. However, because an array is a collection, we also need to specify the type of the elements in the array. We specify the types of the elements in the Array using the Array<type> or type[] syntax

let arr:number[] = [1, 2, 3, 4, 5];
letarr2:Array<number> = [1, 2, 3, 4, 5]; // Array genericsletArr3: string [] = [" 1 ", "2");let arr4:Array<string> = ["1"."2"];
interface NumberArray { 
    [index:number]: number
}
letFibonacci: NumberArray = [1, 2, 3, 4]Copy the code


Enums type

Lists all available values. The default initial value for an enumeration is 0. You can adjust the initial range:

Enum REN {nan, nv, yao}console.log(ren.yao) // returns 2. enum REN { nan ='male',    
    nv = 'woman',    
    yao= 'monster'} console.log(ren.yao) // Returns the word demonCopy the code


Tuples Tuple

Tuple types allow you to represent an array with a known number and type of elements. The elements need not be of the same type (arrays combine objects of the same type, whereas tuples combine objects of different types).

let tuple: [number,string,string]
tuple = ['sun', 18.'jun'] // err // Typescript warns if indexing rules for tuples are not followed.Copy the code


Any type

Any is the default type, and variables of type allow values of any type:

let notSure: any = 10
let notSure2: any[] = [1,"2".false]Copy the code


Void type

JavaScript has no concept of a Void value. In TypeScirpt, Void can be used to represent functions that return no value:

function alertName(): void {  
    console.log('My name is sunjun')}Copy the code


The joint type

let name: string | number = 'sunjun'/ / connector | name = 1Copy the code


Never type

The never type represents the types of values that never exist. For example, the never type is the return type of function expressions or arrow function expressions that always throw an exception or have no return value at all; Variables can also be of type never, when they are bound by type protection that is never true.

// A function that returns never must have an unreachable endfunctionerror(message: string): never { throw new Error(message); } // The inferred return value type is neverfunction fail() {    
    return error("Something failed"); } // A function that returns never must have an unreachable endpointfunction infiniteLoop(): never {    
    while (true) {}}Copy the code


The generic

function Hello<T>(arg:T):T {    
    return arg
}
let outPut = Hello<string>('Hello')
let output2 = Hello('Hello')
let output3 = Hello(123)
console.log(outPut)
console.log(outPut2)
console.log(outPut3)Copy the code

We add a type variable T to the Hello function to help us capture the type passed in by the user (for example: string). The Hello function is called generic because it can be applied to multiple types. Output and output2 have the same effect in the code. The second method, which is more general, makes use of type inference — that is, the compiler automatically helps us determine the type of T based on the parameters passed in


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).lengthCopy the code

The other is the AS syntax

let someValue: any = "this is a string"
let strLength: number = (someValue as string).lengthCopy the code

Note: Both 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.


interface

Is a specification, usually used to define a specification (or data structure) that must be followed.

interface User {  
    name: string  
    age: number
}
interface Name {   
    name: string
}
interface User extends Name {   
    age: number
}
let user:User = { 
    name:'sunjun', 
    age:18 
}
console.log(user)Copy the code


Declare file

// List a few common ones:declareVar declares global variablesdeclare functionDeclare global methodsdeclareClass declares a global classdeclareEnum Indicates the global enumeration typedeclareGlobal extends global variablesdeclareModule Extension moduleCopy the code


Optional argument (? :) and non-empty assertion operators (! .).

functionbuildName(a: string, b? : string) {return a + ' '+ b } //b? Indicates whether parameter B can be passed or not. // error demonstration buildName("a"."b"."c"// Correctly demonstrate buildName("a"// Correctly demonstrate buildName("a"."b")
lets = e! .name // asserts that e is non-null and has access to the name attribute, which can be used to determine that the value of the variable must not be null.Copy the code


Vue + ts hands type

vue create my-appCopy the code




Customize the detail configuration

Use class-style component syntax? (Y/n) : whether to use the class-style component syntax Y

Use Babel alongside TypeScript for auto-detected polyfills? (Y/n) : whether to use Babel to escape Y

Use history mode for router? Requires proper server setup for index fallback in production (Y/n) : Requires proper server setup for index fallback in production

Pick a linter/formatter config: Select a linter

Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Select a pre-processing mode

Pick Additional Lint Features: Select save-time checking/committ-time checking

Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? (Use arrow keys) : Select a location to store the configuration information separately or to merge it with package.json

Save this as a preset for future projects? (y/N) : indicates whether to save the current preset

// shims-tsx.d.ts, batch named several internal modules in global variable. import Vue, { VNode } from'vue';
declare global {  
    namespace JSX {    
        // tslint:disable no-empty-interface    
        interface Element extends VNode {}    
        // tslint:disableno-empty-interface interface ElementClass extends Vue {} interface IntrinsicElements { [elem: string]: any; }}} // shims-vue.d.ts tells TypeScript *.vue files to be processed by the vue module.declare module '*.vue' {  
    import Vue from 'vue';  
    exportdefault Vue; } / /declare: When using a third-party library, we need to reference its declaration file to obtain the corresponding code completion, interface prompts and other functions.Copy the code


Vue component Ts notation

@emit Specifies the event Emit. You can use this modifier or use this.$Emit () directly.

Inject Specifies dependency injection

@ Mixins mixin injection

@ Model to specify the Model

Specifies the Prop @ Prop

@ dojo.provide dojo.provide specified

@ Watch Watch specified

@Component export from vue-class-component

See specific decorator syntax: https://github.com/kaorun343/vue-property-decorator#PropSync

For example

import {  Component, Prop, Watch, Vue } from 'vue-property-decorator'
@Component
export class MyComponent extends Vue {   
    dataA: string = 'test'   
    @Prop({ default: 0 })   
    propA: number   
    // watcher   
    @Watch('child')   
    onChildChanged (val: string, oldVal: string) {}   
    @Watch('person', { immediate: true, deep: true}) onPersonChanged (val: Person, oldVal: Person) {}Copy the code

Parsed into our ordinary VUE

export default {  
    data () {    
        return {       
            dataA: 'test'    
        }  
    },  
    props: {     
        propA: {       
            type: Number,        
            default: 0     
        }  
    },  
    watch: {    
        'child': {        
            handler: 'onChildChanged',        
            immediate: false,        
            deep: false    
        },    
        'person': {        
            handler: 'onPersonChanged',        
            immediate: true,        
            deep: true    
        }  
    },  
    methods: {      
        onChildChanged (val, oldVal) {},      
        onPersonChanged (val, oldVal) {}  
    }
}Copy the code


vuex-class

Vuex-class is a library based on Vue, vuex, vuUe-class-Component. Like vue-property-decorator, vuex-class provides four decorators and a namespace. Solve vuex in.vue file on the inconvenient problem.

@State @Getter @Mutation @Action namespace

import Vue from 'vue'import Component from 'vue-class-component'
import {  State,  Getter,  Action,  Mutation,  namespace } from 'vuex-class'
const someModule = namespace('path/to/module')
@Component
export class MyComp extends Vue {  
    @State('foo') stateFoo  
    @State(state => state.bar) stateBar  
    @Getter('foo') getterFoo  
    @Action('foo') actionFoo  
    @Mutation('foo') mutationFoo  
    @someModule.Getter('foo') moduleGetterFoo  
    created () {        
        this.stateFoo // -> store.state.foo    
        this.stateBar // -> store.state.bar    
        this.getterFoo // -> store.getters.foo    
        this.actionFoo({ value: true }) // -> store.dispatch('foo', { value: true })    
        this.mutationFoo({ value: true }) // -> store.commit('foo', { value: true })    
        this.moduleGetterFoo // -> store.getters['path/to/module/foo']}}Copy the code

So far, the usage of ts in.vue files has been covered. I also believe that small partners see this, to its general grammar sugar also have a certain understanding