Abstract: instead of replacing vue with ts, you can insert ts files in the original project. At present, it is only the practical stage, t...
instead of replacing vue with ts, you can insert ts files in the original project. At present, it is only the practical stage, the transition to ts.
Usage of ts
Type checking, direct compilation to native js and introduction of new syntax sugars
Why use ts?
TypeScript should be designed to address the "pain points" of JavaScript: weak typing and no namespaces It makes it difficult to modularize and is not suitable for the development of large-scale programs. In addition, it also provides some syntax candy to help you practice object-oriented programming more easily.
Typescript can not only restrict our coding habits, but also play the role of annotations. When we see a function, we immediately know the use of the function and what value we need to pass. The type of return value is clear at a glance, which greatly improves the maintainability of large projects. Nor will it cause developers to lift a rock and drop it on their own feet. Why did we choose TypeScript?
- Excellent tools in TypeScript
- TypeScript is a superset of JavaScript
- TypeScript makes abstractions clearly visible
- TypeScript makes the code easier to read and understand
Yes, I know it doesn't seem intuitive. Let me give an example to illustrate what I mean. Let's take a look at the function jQuery.ajax (). What information can we get from its signature?
The only thing we know for sure is that this function has two parameters. We can guess these types. Maybe the first is a string and the second is the configuration object. But this is just a guess. We may be wrong. We don't know what options enter the setting objects (their names and types), or what the function returns.
It is impossible to call this function without checking the source code or documentation. Checking the source code is not a good choice, the purpose of having functions and classes Is to use them without knowing how to implement them, let me put it another way, We should rely on their interfaces, not their implementation. We can check the documents. But this is not the best development experience-it takes extra time, and the documentation is often out of date.
So, although it is easy to read jQuery.ajax (url,settings). To really understand how to call this function, we need to read its implementation or its documentation.
The following is a type version:
It gives us more information.
- The first argument to this function is a string.
- Setting parameters are optional. We can see all the options that can be passed to the function. Not only their names, but also their types.
- The function returns a JQueryXHR object, and we can see its properties and functions.
Typed signatures must be longer than untyped signatures. But: string,:JQueryAjaxSettings and JQueryXHR are not chaotic. They are important documents to improve the understandability of the code. We can understand the code more deeply. You don't have to go deep into the implementation or read the document. My personal experience is that I can read typed code faster. Because types provide more context to understand the code.
Is ts easy to learn?
One of the highlights of TypeScript is that it does not abandon the syntax of JavaScript and start over. Instead, it makes a superset of JavaScript (this credit should be credited to Anders), so any legal JavaScript statement is legal under TypeScript. In other words, the cost of learning is very low, if you have a deeper understanding of JavaScript So you can actually get started with TypeScript very quickly. Because it is designed for the usage and conventions of JavaScript.
Some simple examples can be understood at a glance:
Basic type
Let isDone: boolean = false; // Boolean Let decLiteral: number = 6; // number Let name: string = "bob"; // string Let list: number [] = [1,2,3]; // Array ... ...
Interface
Function printLabel (labelledObj: {label: string}) {console.log (labelledObj.label) } let myObj = {size: 10, label: "Size 10 Object"} PrintLabel (myObj)
The Type Checker looks at the calls to printLabel. PrintLabel has one parameter And require that the object parameter have a property of type string named label. It is important to note that the object parameters we pass in actually contain a lot of properties. But the compiler only checks whether those required attributes exist and if their types match. Of course, there are some advanced uses, so I won't introduce you too much here and learn more about it.
How to apply ts in vue projects?
1.Install ts first
Npm install-save-dev typescript npm install-save-dev ts-loader
2.Create the tsconfig.json file in the root directory
{ "compilerOptions": { "experimentalDecorators": true "emitDecoratorMetadata": true "lib": ["dom", "es2016"] "target": "es5" } "include": [". / src/**/*"] }
3.Add ts-loader to the configuration
{ Test: / / .tsx? $/ Loader: 'ts-loader', exclude: / node_modules/, options: { AppendTsSuffixTo: [/\ .vue $/] } }
4.Finally, add the .ts suffix to OK, in the webpack.base.conf.js file
Now we can use the ts file in our original project.
How to practice?
1.How to reference a ts file in js?
Since the js file has no type checking, when we introduce the ts file. Ts files are converted to js files, so the method type detection mechanism that references ts files in js files does not take effect. That is to say, there is a type checking mechanism only in ts files.
So how do you use the type checking mechanism in js files? The editor encapsulates a set of typeCheck decorator methods for reference only! The usage is as follows:
@ typeCheck ('object','number') deleteItem (item,index) {}
Detect deleteItem method parameters: item is of object type and index is of number type. If the type does not match, an exception will be thrown. Some of the codes are presented:
const _check = function (checked,checker) {
check:
for(let i = 0; i < checked.length; i++) {
if(/(any)/ig.test(checker[i]))
continue check;
if(_isPlainObject(checked[i]) && /(object)/ig.test(checker[i]))
continue check;
if(_isRegExp(checked[i]) && /(regexp)/ig.test(checker[i]))
continue check;
if(Array.isArray(checked[i]) && /(array)/ig.test(checker[i]))
continue check;
let type = typeof checked[i];
let checkReg = new RegExp(type,'ig')
if(!checkReg.test(checker[i])) {
console.error(checked[i] + 'is not a ' + checker[i]);
return false;
}
} return true;
} /**
* @description test type
* 1.It is used to check the type of the function parameter. If the type is wrong, the error will be printed and the function will not be executed again;
* 2.Type detection ignores case, for example, string and String can be recognized as string types;
* 3.Add any type, indicating that any type can be detected;
* 4.Multiple types can be detected, such as "number array". Both types can pass the detection. Regular detection ignores connectors;
*/
export function typeCheck() {
const checker = Array.prototype.slice.apply(arguments);
return function (target, funcName, descriptor) {
let oriFunc = descriptor.value;
descriptor.value = function () {
let checked = Array.prototype.slice.apply(arguments);
let result = undefined;
if(_check(checked,checker) ){
result = oriFunc.call(this,...arguments);
} return result;
}
}
};
Ts's type checking with typeCheck has basically met our needs.
2.How to reference js files in ts?
Because there is no type detection in the js file, the ts file is converted to the any type when it is introduced into the js file. Of course, we can also declare the type in the .d.ts file.
Such as global.d.ts file.
Of course, sometimes we need to use some libraries, but there are no declaration files. Then when we refer to it in the ts file, it will be undefined. What should we do at this time?
For example, when I want to use 'query-string'' in the util.ts file, we will quote:
Import querystring from 'query-string'
However, when you print querystring, it is undefined. How to solve the problem? The editor's method is for reference only.
Create a new module.js file
Import querystring from 'query-string'; export const qs = querystring
Utile.ts file
Import {qs} from'. / module.js'
Solved. Print qs is no longer undefined, you can use the qs library normally.
At this point, this article ends the introduction of the configuration of ts in vue. This article only represents my personal views, taking into account the expansibility of the project. So instead of replacing all of them with ts, we just try to introduce ts into vue. There is still a lot of room for improvement.