Home >Web Front-end >JS Tutorial >Tips for using ts in vue
Note: This article is not to replace all vue with ts, but to embed ts files in the original project. It is currently only in the practice stage and the transition to ts conversion process.
Type checking, direct compilation to native js, introduction of new syntax sugar
The design purpose of TypeScript should be to solve the "pain points" of JavaScript: weak types and no namespace, making it difficult to modularize and not suitable for development Large programs. In addition, it also provides some syntactic sugar to help everyone practice object-oriented programming more conveniently.
typescript can not only constrain our coding habits, but also play the role of comments. When we see a function, we can immediately know the usage of this function. Need It is clear at a glance what value is passed and what type the return value is, which greatly improves the maintainability of large projects. It won't cause developers to shoot themselves in the foot.
Angular: Why did we choose TypeScript?
Excellent tools in TypeScript
TypeScript is a superset of JavaScript
TypeScript makes abstractions visible
TypeScript makes code easier to read and understand
Yes, I know this 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 takes two parameters. We can guess at these types. Maybe the first is a string and the second is a configuration object. But this is just speculation and we could be wrong. We don't know what options go into the settings object (their names and types), or what the function returns.
It is impossible to call this function without checking the source code or documentation. Examining the source code is not an option - 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 implementations. We could check the documentation, but it's 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 parameter of this function is a string.
Setting parameters is optional. We can see all the options that can be passed into 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 are definitely longer than untyped ones, but :string, :JQueryAjaxSettings and JQueryXHR are not cluttered. They are important documents that improve the understandability of your code. We can understand the code more deeply without having to dive into the implementation or read the documentation. My personal experience is that I can read typed code faster because the types provide more context to understand the code.
Excerpted from Angular: Why did we choose TypeScript?
One of the design highlights of TypeScript is that it does not abandon the syntax of JavaScript and start a new one, but instead makes it a superset of JavaScript (this credit should be credited to Anders), so that any legal JavaScript statement It is legal under TypeScript, which means that the learning cost is very low. If you have a deeper understanding of JavaScript, you can actually get started with TypeScript quickly, because its design is based on JavaScript usage habits and conventions.
Some simple examples, easy to understand at a glance:
Basic type
let isDone: boolean = false; // 布尔值 let decLiteral: number = 6; // 数字 let name: string = "bob"; // 字符串 let list: number[] = [1, 2, 3]; // 数组 ... ...
Interface
function printLabel(labelledObj: { label: string }) { console.log(labelledObj.label); } let myObj = { size: 10, label: "Size 10 Object" }; printLabel(myObj);
The type checker will check the call to printLabel . printLabel has one parameter, and requires that this object parameter has an attribute named label of type string. It should be noted that the object parameter we pass in will actually contain many properties, but the compiler will only check whether those required properties exist and whether their types match.
Of course there are some advanced usages, I won’t introduce them too much here, learn more
1. First install ts
npm install --save-dev typescript npm install --save-dev ts-loader
2. Create a tsconfig.json file in the root directory
<code>{ "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, "lib": ["dom","es2016"], "target": "es5" }, "include": ["./src/**/*"] <br>}</code>
3. Add ts-loader
{ test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: { appendTsSuffixTo: [/\.vue$/], } }
4 in the configuration. Finally, add the .ts suffix and it will be OK. In webpack.base.conf. js file
#Now we can use the ts file in our original project.
1. How to reference ts files in js?
Since js files do not have type detection, when we introduce ts files, the ts files will be converted into js files, so the method type detection mechanism that references ts files in js files will not take effect. In other words, there is a type detection mechanism only in the ts file.
So how to use the type detection mechanism in js files? The editor has encapsulated 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 object type, index is number type, if the type does not match, an exception will be thrown
Part of the code is presented:
<code>const _check = function (checked,checker) { check: <br> for(let i = 0; i < checked.length; i++) { <br> if(/(any)/ig.test(checker[i])) <br> continue check; <br> if(_isPlainObject(checked[i]) && /(object)/ig.test(checker[i]))<br> continue check; <br> if(_isRegExp(checked[i]) && /(regexp)/ig.test(checker[i]))<br> continue check; <br> if(Array.isArray(checked[i]) && /(array)/ig.test(checker[i]))<br> continue check; <br> let type = typeof checked[i]; <br> let checkReg = new RegExp(type,'ig') <br> if(!checkReg.test(checker[i])) { <br> console.error(checked[i] + 'is not a ' + checker[i]); <br> return false; } } return true; } /** * @description 检测类型 * 1.用于校检<a href="http://www.php.cn/wiki/147.html" target="_blank">函数参数</a>的类型,如果类型错误,会打印错误并不再执行该函数; * 2.类型检测忽略大小写,如string和String都可以识别为字符串类型; * 3.增加any类型,表示任何类型均可检测通过; * 4.可检测多个类型,如 "number array",两者均可检测通过。正则检测忽略连接符 ; */ export function typeCheck() { <br> const checker = Array.prototype.slice.apply(arguments); <br> return function (target, funcName, descriptor) { <br> let oriFunc = descriptor.value; descriptor.value = function () { <br> let checked = Array.prototype.slice.apply(arguments); <br> let result = undefined; <br> if(_check(checked,checker) ){ result = oriFunc.call(this,...arguments); } return result; } } };</code>
ts type detection combined with typeCheck has basically met our needs.
2. How to reference js files in ts?
Since there is no type detection in the js file, the ts file will be converted to the any type when it is imported 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 is no declaration file, then we add it in the ts file It will be undefined when referenced. What should we do at this time?
For example, when I want to use ‘query-string’ in the util.ts file, we will quote it like this:
import querystring from 'query-string';
However, when you print querystring, it is undefined. How to solve it? 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. Printing qs is no longer undefined, and you can use the qs library normally.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Basic knowledge of html in the front-end
The above is the detailed content of Tips for using ts in vue. For more information, please follow other related articles on the PHP Chinese website!