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.
What is the use of ts?
Type checking, direct compilation to native js, introduction of new syntax sugar
Why use ts?
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?
ts Is it easy to learn?
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
How to apply ts in vue project?
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.
How to practice?
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Win11 Tips Sharing: One trick to skip Microsoft account login Windows 11 is the latest operating system launched by Microsoft, with a new design style and many practical functions. However, for some users, having to log in to their Microsoft account every time they boot up the system can be a bit annoying. If you are one of them, you might as well try the following tips, which will allow you to skip logging in with a Microsoft account and enter the desktop interface directly. First, we need to create a local account in the system to log in instead of a Microsoft account. The advantage of doing this is

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.
