What’s the use of TS
Type checking, es6 embrace, partial esNext draft support, direct compilation to native JS, new syntactic sugar introduced
Why use TS
TypeScript should be designed to address JavaScript’s “pain points” : weak typing and lack of namespaces make it difficult to modularize and make it unsuitable for large applications. It also provides some syntax candy to help you practice object-oriented programming more easily.
Typescript not only constrains our coding habits, but also annotates a function so that when we see it, we immediately know how to use it, what values need to be passed, and what types of values are returned, making it much easier to maintain large projects.
Compilation error, will the compilation result be generated?
The answer is yes, of course in tsconfig.json configuration, noEmitONError
Tsconfig. json file configuration
Haven’t done
Based on summarizing
The data type
- Boolean, number, string, null, undefined, Symbol
- Data of the type undefined and NULL can only be assigned to undefined and NULL, but this type is a subtype of all types
- Empty void type
// undefined and null are subtypes of all types and can be assigned
let num: Symbol = undefined; sslet num: number = undefined;
// undefined can only be given as undefined
let u: undefined = undefined;
let n: null = null;
Copy the code
- Any and type inference
// In TS, a variable is declared as the default type if its type is not defined
let str;
str = 'I am strgting';
str = 1024;
// No type is defined
let num= 124;
// let num:number = 124
Copy the code
Multiple possible attributes
// Only common attributes of possible attributes can be accessed
function getLength(param: string| number) {
return param.length;
}
// An error is reported because length is not a common property of the types sting and number
// Use type aliases
type possibleType = string | number;
function getLength(param: possibleType) {
return param.length;
}
Copy the code
Concepts of interfaces
- In TS, interfaces include an abstraction of behavior, implemented by classes (implements)
- It also includes descriptions of object contours
Object interface – dynamic property
Mandatory and optional parameter types are subsets of dynamic property types, so all types must be set when dynamic property types are set
interface userinfo {
"memberId": number,
"uName": string,
"employeeId": string,
"datetime": string,
"platformList"? :Array<platform>,
[propName: string]: string | number | Array<platform> | undefined
}
Copy the code
The constraint of a read-only property
Note that a read-only property is binding only when the object is first assigned, not when the property is assigned to it
Interface – The implementation of abstract methods
exportinterface ISRequest { fetch(url: string, arg? :Object, callback? :Function) :Promise<Object>;
}
export class SafeRequest implements ISRequest {
public asyncfetch(url: string, arg, callback? :Function) :Promise<Object> {
return new Promise((resolve, reject) = >{})}Copy the code
Represent arrays with interfaces
interface NumberArray {
[index: any]: number
}
let numArr: NumberArray = [1.2.3]
Copy the code
Type of function
- This parameter is optional and must come after the mandatory parameter
- Parameter Default Value
function buildName(firstName: string, lastName? : string) {}Copy the code
- Parameter recognition with default values is optional
- The remaining parameters
Types of assertions
// < type > value
// Value as type
Copy the code
Doubt — statement document
When using a third-party library, we need to reference its declaration file to get the corresponding code completion, interface prompts and other functions.
Where is the declaration file?
- Bind with the NPM package
- The maintainer of the NPM package does not provide a declaration file, only someone else can publish the declaration file to @types
- Write your own declaration
NPM package declaration file and global variable declaration file
In the declaration file of the NPM package, using DECLARE no longer declares a global variable, but only a local variable in the current file. These type declarations are applied only after export is exported in the declaration file and then imported by the user import. ###### Declare Global Use Declare Global to extend the types of global variables in NPM packages or UMD libraries
Built-in objects
Built-in object query — clicking ESMAScript provides Boolean, Error, Date, RegExp
interface obj = {
param: Function
param: Promise
}
Copy the code
Enumeration — “bidirectional mapping of data
enum companyList= {1: 'aaa'.2: 'bbb'}
var companyList = {
1: 'aaa'.2: 'bbb'.aaa: 1.bbb: 2
}
Copy the code
Vue in Typescript
Three tool
- vue-component-class
- Methods can be declared directly as class member methods.
- Computed properties can be declared as class property accessors.
- The default data is treated as a class attribute
- The data, Render, and vue lifecycle hooks are directly class member methods; keep these names and do not conflict
- For other configuration items, such as prop, Componets, etc., pass to decorator functions
import Vue from 'vue';
import Component from 'vue-componet-class';
Component.resgisterHooks([
'beforeRouteEnter'
])
@Componnet({
props: {},components: {}})export default class App extends Vue {
// aa = '';
Aa is a string and can only be assigned to aa
// It is best to use the first word after the first word
// data
public tableModelItems: Array<any>;
constructor() {
super(a);this.tableModelItems = [];
}
// computed
public get filterTableData() {
return this.tableData.filter((i: any) = > i.refundStatus === 0).length
/ / method
// Declare the period
// What about the lifecycle hook of the routing function
beforeRouteEnterf() {
next() // You have to write it, or you can't play it. Why?}}}Copy the code
- vue-property-decorator(Relies on vue-component-class to provide more decorators, - @emit - @inject - @prop - @provide - @watch - vuex-class (connected to vue and vuex) jsCopy the code
Unsolved bugs
Error – type error reported
Add the type of script
<script lang="ts"></script><! Otherwise, the following type fails:Copy the code
Vue failed to mount Propoty (if still popular, restart ide)
Declare mount again
<! --inject-->import _Vue from 'vue'
import moment from "moment";
export default {
install(Vue: typeof _Vue, options: any) {
Vue.prototype.$moment = moment;
Vue.prototype.$log = (a)= > {
console.log(new Date())}}} <! --types-->import Vue from 'vue'
declare module 'vue/types/vue' {
interface Vue {
$moment: Function
$log: Function}}Copy the code
The. Vue file is not recognized in ts
By default, TypeScript only recognizes.ts files, not.vue files. Import Component from ‘components/component.vue’
Vuex -class Emit error passing argument to parent component
@emit("reset")
reset(role, this.formData){} <! -- error -->Copy the code
Error –> Optional parameter bursts red
Refer to the link
-
Vue + TS quick start
-
Ts Easy to understand, relatively clear documents
-
Ts of the website
-
Especially great views on TS + VUE
-
Ts practice of Ant Financial