Note: This paper does not replace vue with ts, but can implant ts files in the original project, which is only a practical stage and a transition to ts transformation.
What's the use of ts?
Type checking, direct compilation to native js, and introduction of new syntax sugar.
Why use ts?
TypeScript should be designed to solve the "pain point" of JavaScript: weak typing, no namespace, difficult to modularize, and not suitable for developing large-scale programs. In addition, it also provides some grammar candy to help you practice object-oriented programming more conveniently.
Typescript can not only constrain our coding habits, but also play the role of annotation. When we see a function, we can immediately know the usage of the function, what value needs to be passed and what type of return value is, which greatly improves the maintainability of large-scale projects. It won't let developers shoot themselves in the foot.
Angular: Why do we choose TypeScript?
Excellent tools in typed manuscripts
TypeScript is a superset of JavaScript.
TypeScript makes abstraction clearly visible.
TypeScript makes the code easier to read and understand.
Yes, I know it doesn't seem intuitive. Let me illustrate what I mean with an example. Let's take a look at this 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 one is a string and the second one is a configuration object. But this is just a guess. We may be wrong. We don't know what options are in the setting objects (their names and types), and we don't know what the function returns.
We can't 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. In other words, 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 documents are often out of date.
Therefore, although jQuery.ajax(url, settings) is easy to read, to really understand how to call this function, we need to understand its implementation or its documentation.
The following are font versions:
It gives us more information.
The first parameter of this function is a string.
Setting parameters is optional. We can see all the options that can be passed into the function, including not only their names, but also their types.
This function returns a JQueryXHR object, and we can see its properties and functions.
Typed signatures are certainly longer than untyped signatures, but: string,: JQueryAjaxSettings and JQueryXHR are not confused. They are important documents to improve code intelligibility. We can understand the code more deeply without going deep into implementation or reading documents. My personal experience is that I can read typed code faster because types provide more context to understand the code.
Excerpted from Angular: Why do we choose TypeScript?
Is ts studious?
One of the highlights of TypeScript's design is that it has not abandoned the grammar of JavaScript, but made a superset of JavaScript (this credit should be recorded on Anders), so that any legal JavaScript statement is legal under TypeScript, that is, the learning cost is very low. If you have a deep understanding of JavaScript, you can actually get started with TypeScript quickly, because its design is based on the usage habits and conventions of JavaScript.
Some simple examples can be understood at a glance:
Basic type
Let isDone:boolean = false;; //Boolean value
Let decliteral: number = 6; //Numbers
let name:string = " bob "; //String
let list: number[] = [ 1,2,3]; //array
...
...
Engagement/interface
Function printlabel (labelledobj: {label: string}) {console.log (labelledobj.label);
} let myObj = { size: 10,label:“Size 10 Object”};
print label(myObj);
The type checker looks at the call to printLabel. Printlabel has a parameter, and this object parameter needs to have an attribute of type string named label. It should be noted that the object parameters we passed in actually contain many attributes, but the compiler will only check whether those necessary attributes exist and whether their types match.
Of course, there are some advanced usages, so I won't introduce them here. Learn more.
How to apply ts in vue project?
1. Install ts first.
Npm Installation Save Development Type Script npm Installation Save Development ts Loader
2. Create the tsconfig.json file in the root directory.
{
"Compiler Options": {
"Experimental Recorder": Yes,
"emit data": really,
" lib": ["dom "," es20 16"],
"Target": es5
},
"contain": [". /src/**/*"] }
3. Add ts-loader to the configuration.
{
Test:/\. tsx? $/,
Loader: "ts-loader", excluding: /node_modules/, option: {
appendTsSuffixTo: [/\。 vue$/],
}
}
4. Finally, add. Ts suffix, under the webpack.base.conf.js file.
Now we can use ts files in the original project.
How to practice?
1. How to reference ts files in js?
Because js file has no type detection, when we import ts file, ts file will be converted into js file, so the method type detection mechanism of referencing ts file in js file will not take effect. In other words, only in ts files will there be a type detection mechanism.
So how to use the type detection mechanism in js file? Bian Xiao has encapsulated a set of decorative methods of typeCheck for reference only! Usage is as follows:
@typeCheck('object ',' number') deleteItem(item,index) {}
Detects the parameters of the deleteitem method: item is of type object and index is of type number, and an exception will be thrown if the types do not match.
Part of the code is as follows:
const _check = function (checked,checker) {
Check: for (let I = 0;; I < checked. Length; I++) {if (/(any)/ig.test (checker [I])) continue to check; if(_ isPlainObject(checked[I])& amp; & (object)/ig.test (checker [I])) continue to check; if(_ is regexp(checked[I])& amp; & (regexp)/ig.test (checker [i])) to continue the check; if(array . isarray(checked[I])& amp; & (array)/ig.test (checker [I])) continue to check; let type = type of checked[I]; Suppose checkReg = new RegExp(type,' ig') if (! Checkreg.test (checker [I]) {console.error (checked [I]+'not'+checker [I]); Returns false
}
} returns true
} /**
* @ Describe the detection type.
* 1. Used to check the type of function parameters. If the type is wrong, an error will be printed and the function will not be executed;
* 2. Type detection ignores case, such as String and string can be recognized as string types;
* 3. Adding any type means that any type can pass the test;
* 4. Various types can be detected, such as "number array", both of which can be detected. Conventional detection ignores connectors;
*/
The export function typecheck () {constchecker = array.prototype.slice.apply (arguments); Return function (target, funcName, descriptor) {let ori func = descriptor. value;
descriptor . value = function(){ let checked = array . prototype . slice . apply(arguments); Assumed result = undefined; if(_check(checked,checker) ){
Result = oriFunc.call(this, ... argument);
} return the result;
}
}
};
Type detection of ts combined with typeCheck has basically met our needs.
2. How to reference js files in ts?
Because there is no type detection in js file, ts file will be converted into any type when js file is introduced. Of course, we can also. D.ts file.
Such as the global.d.ts file.
Of course, sometimes we need to use some libraries, but there are no declaration files, so when we refer to ts files, there will be undefined situations. What should we do at this time?
For example, when I want to use'' query-string'' in the util.ts file, we will refer to it like this:
Import querystring from "query-string"
However, when you print querystring, it is undefined. How to solve it? Bian Xiao's method is also for reference only.
Create a new module.js file.
Import querystring export constqs = querystring from "query-string"
Utile.ts file
Import {qs} from'. /module . js ';
Solved it. Printing qs is no longer undefined, and qs library can be used normally.
At this point, this paper ends by introducing ts configuration in vue. This article only represents personal views. Considering the expansibility of the project, I didn't completely replace it with ts, but tried to introduce ts into vue. There is still much room for improvement. If you have better suggestions and opinions, please contact me!