Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basic ways to use Typescript in Vue3

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "what are the basic uses of Typescript in Vue3". In daily operation, I believe that many people have doubts about the basic use of Typescript in Vue3. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "what is the basic use of Typescript in Vue3?" Next, please follow the editor to study!

Variable declares the basic type let isDone: boolean = falselet num: number = 1let str: string = 'vue3js.cn'let arr: number [] = [1,2,3] let arr2: Array = [1,2,3] / generic array let obj: Object = {} let u: undefined = undefined;let n: null = null; type supplement

Enumerate Enum

Use enumerated types to give a friendly name to a set of values

Enum LogLevel {info = 'info', warn =' warn', error = 'error',}

Tuple Tuple

Allows the elements of the array to be of the same type. For example, you can define a pair of tuples with values of type string and number, respectively

/ / Declare a tuple typelet x: [string, number]; / / Initialize itx = ['hello', 10]; / / OK// Initialize it incorrectlyx = [10,' hello']; / / Error

Arbitrary value Any

Represents any type, usually used for uncertain content, such as from user input or a third-party code base

Let notSure: any = 4 * notSure = "maybe a string instead"; notSure = false; / / okay, definitely a boolean

Null Void

In contrast to any, it is usually used in functions to indicate that no value is returned

Function warnUser (): void {console.log ("This is my warning message");}

Interface interface

Type contract, just like we usually have to define fields in order to transfer the server interface.

The following example: point and Point types must be the same, and one more and one less is not allowed.

Interface Point {x: number y: number zoning: number readonly l: number} const point: Point = {x: 10, y: 20, z: 30, l: 40} const point2: Point = {x:'10, y: 20, z: 30, z: 40} / / Error const point3: Point = {x: 10, y: 20, z: 30} / / Error const point4: Point = {x: 10, y: 20, z: 30, l: 40, m: 50} / / Error

Optional or read-only? Indicates optional parameter, and readonly indicates read-only

Const point5: Point = {x: 10, y: 20, l: 40} / normal point5.l = 50 / / error function parameter type and return value type function sum (a: number, b: number): number {return a + b}

Use with interface

Interface Point {x: number y: number} function sum ({x, y}: Point): number {return x + y} sum / / 3 generics

The meaning of generics lies in the reusability of functions. Design principles hope that components can support not only current data types, but also future data types.

such as

According to the original design function of the business, the input parameter identity is String

Function identity (arg: String) {return arg} console.log (identity ('100'))

Business iterative process parameters need to support Number

Function identity (arg: String) {return arg} console.log (identity) / / Argument of type '100' is not assignable to parameter of type' String'. Why not use any?

Using any will lose some information. We can't determine what type the return value is. Generics can guarantee that the input parameter is of the same type as the return value. It is a special variable that is only used to represent the type, not the value.

Syntax (arg:T): t, where T is a custom variable

Const hello: string = "Hello vue!" function say (arg: t): t {return arg;} console.log (say (hello)) / / Hello vue! Generic constraint

We used the same example and added a console, but unfortunately, we got it wrong, because generics cannot guarantee that every type has a .length property.

Const hello: string = "Hello vue!" function say (arg: t): t {console.log (arg.length) / / Property 'length' does not exist on type' length' does not exist on type. Return arg;} console.log (say (hello)) / / Hello vue!

From this, we also see a difference from any. If we want to end the battle at the constraint level, we need to define an interface to describe the constraints.

Interface Lengthwise {length: number;} function say (arg: t): t {console.log (arg.length) return arg;} console.log (say (1)) / / Argument of type'1' is not assignable to parameter of type 'Lengthwise'.console.log (say ({value:' hello vouchers, length: 10})) / {value: 'hello vouchers, length: 10} crossover type

Cross type (Intersection Types), which combines multiple types into a single type

Interface foo {x: number} interface bar {b: number} type intersection = foo & barconst result: intersection = {x: 10, b: 20} const result1: intersection = {x: 10} / / error union type

A Union Types, indicating that a value can be one of several types. We use a vertical bar | separate each type, so number | string | boolean indicates that a value can be number, string, or boolean

Type arg = string | number | booleanconst foo = (arg: arg): any = > {console.log (arg)} foo (1) foo ('2') foo (true) function overload

Function overloading (Function Overloading) allows you to create subroutines with the same name but different input and output types or different numbers, which can be simply understood as the ability of a function to perform multiple tasks.

For example, we have an add function, which can receive parameters of type string for splicing, or receive parameters of type number for addition.

Function add (arg1: string, arg2: string): stringfunction add (arg1: number, arg2: number): number// implementation function add (arg1: t, arg2: U) {/ / We should pay attention to strictly judging whether the types of the two parameters are equal You can't simply write an arg1 + arg2 if (typeof arg1 = 'string' & & typeof arg2 =' string') {return arg1 + arg2} else if (typeof arg1 = 'number' & & typeof arg2 =' number') {return arg1 + arg2}} add (1,2) / / 3add ('1') / /'12 'summary

Through this article, I believe that you will no longer feel strange to Typescript.

Let's take a look at how to write Typescript in the Vue source code. Here we take the defineComponent function as an example. We can use this example, combined with the content of the article, to understand and deepen the understanding of Typescript.

/ / overload 1: direct setup functionexport function defineComponent (setup: (props: Readonly, ctx: SetupContext) = > RawBindings | RenderFunction): {new (): ComponentPublicInstance

< Props, RawBindings, {}, {}, {}, // public props VNodeProps & Props >

} & FunctionalComponent// defineComponent has a total of four overloads. Three / / implementation are omitted here. Close to no-opexport function defineComponent (options: unknown) {return isFunction (options)? {setup: options}: options} this ends the study of "what are the basic uses of Typescript in Vue3". I hope you can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report