TypeScript (1) Type declaration, type inference, union type, interface, function, type assertion, type alias, enumeration

Table of Contents

(1) Introduction

1.The difference between JavaScript and TypeScript

2. Advantages of TypeScript

(2) Used in vue3 project

(3) Type declaration

1.Basic data types

(1)string

(2) number

(3)boolean

(4)null and undefined

2. Reference data type

(1)Array array

(2) Tuple tuple

(3)Object object

3.any and void types

(1)any

(2)void

4. Use typeof to determine the type of a variable

(3) Type inference

(4) Union type

(5)Interface interface

1.Object type

2. Array type (not commonly used)

3. Function type

(6) Function

1. Define functions

2. Optional parameters and default parameters

3. Remaining functions and function overloading

(7) Type assertion

1. Assert a union type to one of the types

2. Assert the parent class to a more specific subclass

3. Assert any type to any

(8) Type aliases and string literal types

1.Type alias

2. String literal type

(9) Enumeration Enum


(1) Introduction

1.The difference between JavaScript and TypeScript

TypeScript is a superset of JavaScript that extends the syntax of JavaScript so that existing JavaScript code can work with TypeScript without any modification. TypeScript provides compile-time static type checking through type annotations.

TypeScript takes existing JavaScript code and compiles only the TypeScript code within it.

2.Advantages of TypeScript

(1) Type safety:Typescript is a statically typed language, which requires the types of variables and functions to be clearly defined during the coding phase. This type safety reduces the likelihood of errors at runtime and improves code readability and maintainability.

(2) Code readability and maintainability:Typescript’s type annotations and strict type checking can make the code easier to read and maintain. It also makes the code clearer and easier to understand, making it less difficult to understand and modify.

(3) Better error troubleshooting:Typescript’s type checking and compilation can find many errors during the coding phase and avoid errors at runtime. This reduces the time and cost of debugging and troubleshooting errors.

(4) Better large-scale project support: Typescript can better support the development of large-scale projects. It provides module systems, namespaces, interfaces, enumerations and other features to make large projects easier to manage and maintain.

(2) Used in vue3 project

Install ts:

npm install -g typescript

Used within a single file component:

<script setup lang="ts">
  // ...
</script>

(3) Type Declaration

The type declaration sets the type for the variable. Subsequent use of the variable can only store values of the specified type.

1.Basic data type

(1)string

// string character type
let str: string = 'csq'
str = '123'

(2)number

//Number type supports decimal, octal, binary, and hexadecimal
let num: number = 77
num = 12
let num1: number = 0b10010 // binary
let num2: number = 0x18 // hexadecimal

(3)boolean

// boolean Boolean type
let bool = true
bool = false

(4)null and undefined

//null and undefined
let nu:null = null
let un:undefined = undefined
// Assigning null and undefined to other data types is prohibited by default
// let n:number = null

Assigning null and undefined to other data types is prohibited by default unless the configuration “strictNullChecks”: false is added in tsconfig.app.json

2. Reference data type

(1)array

//array
// 1. Direct definition
const numArr: number[] = [1, 2, 3]
// 2. Generic definition
const strArr:Array<string> = ['1','2','3']

(2) tuple tuple

Objects of different data types are merged, and the data type and length are defined in advance.

// Tuple tuple
let tarr: [number, string] = [1, '2']
// When pushing, you can add number or string type data
tarr.push(3)
tarr.push('4')

(3)Object object

// object object non-primitive data type (data type other than number, string, boolean)
let obj:object = {}
obj = {
    a:1
}
obj = [] // array is an object
obj = new String() // String class instance is an object
// Values can only be assigned in non-strict mode, otherwise an error will be reported
// obj = null
// obj = undefined

3.any and void type

(1)any

// any can define all data types
let a:any = 1
a = []
a = '123'
let anyArr:any[] = [1,'2',true,{},[]]

(2)void

//void is usually used for functions and the return value is empty
function f():void{
    console.log(111);
}
// After a variable is defined as void, it can only be assigned a value of undefined.
let voi:void = undefined

4. Use typeof to determine the type of a variable

(3) Type Inference

Use type inference to provide type information without explicit type annotations,

let num = 3; // num is inferred as number type

num = abc’ // an error will be reported

This inference occurs when initializing variables and members, setting parameter default values, and determining function return types.

Case inferred as any type:

let g; // At this time, the variable g is inferred to be of type any and can be assigned any value
g = 1;
g = [],
g = undefined

(4) Union type

A type composed of two or more other types, representing a value that may be any of these types

Operation only allowed if valid for every member of the federation

// Union type
let unite: number | string = 1
unite = 'abc'
// unite = false

function show(a: number | string) {
    // toUpperCase function can only be used for string type,
    // a.toUpperCase()
    // Must use operations that can be used by union types
    a.toString()

    console.log(a);
}
show(123)
show('123')
// show(true)

(5)Interface interface

1.Object type

Determine the attributes: name:string;

Optional attributes: age?:number;

Read-only attribute: readonly id:number;

Any attribute: [propsName:string]:any; After any attribute is defined, the number of attributes in the object variable can be more than the number of attributes of the interface.

// 1. ====Object type====
interface Person {
    readonly id: number; // can only be read but not modified
    name: string;
    age?: number; // ?Indicates that this attribute is optional number|undefined
    // Any attribute can only appear once in the interface
    // The key of any attribute is string, the attribute value determines the attribute and the optional attribute type must be a subset of its type
    // [propsName:string]:any,
    [propsName: string]: string | number | undefined;
}

let p: Person = {
    id: 77,
    name: 'csq',
    age: 18,
    sex: 'nv',
    weight: 100
}

2. Array type (not commonly used)

// 2.====Array type====
interface Array {
    [index: number]: string;
}
let arr: Array = ['1', '2', '3']

3. Function type

// 3.====Function type====
interface Fun {
    // (Incoming parameter name: parameter type,...): return value type
    (a: string, b: string): boolean
}
const fun1: Fun = function (a: string, b: string): boolean {
    return b.indexOf(a) != -1
}

(6) function

1. Define function

// 1.====Define function====
// 1. Function declaration: named function
function fun1(a: number, b: number): number {
    return a + b
}
// 2. Function declaration: anonymous function
let fun2 = function (a: number, b: number): number {
    return a + b
}
// 3. Function declaration: complete writing method
let fun3: (a: number, b: number) => number = function (a: number, b: number): number {
    return a + b
}

2. Optional parameters and default parameters

Default parameters: b: string = ‘csq’

Optional parameters: c?: number // Optional parameters must be placed after all confirmed and default parameters

// 2.====Optional parameters and default parameters====
let fun4 = function (a: number, b: string = 'csq', c?: number): string {
    return a + b
}
console.log(fun4(7, '77'));

3. Remaining functions and function overloading

(1)Residual function…rest

es6 new features

// 1. Remaining function
function fun5(a: string, b: string, ...rest: number[]) {
    console.log(rest);
}
fun5('1', '2', 1, 2, 3)

(2) Function overload overload

// 2. Function overloading
// Function overload declaration
function fun6(a: string, b: string): string
function fun6(a: number, b: number): number

function fun6(a: string | number, b: string | number): string | number | void {
    if (typeof a == 'string' & amp; & amp; typeof b == 'string') {
        return a + b //string type
    }
    if (typeof a == 'number' & amp; & amp; typeof b == 'number') {
        return a + b //number type
    }
}
fun6(1, 2)
fun6('1', '2')
// fun6(1,'1')

(7) Type Assertion

Used to manually specify specific types

Two ways to use it: as and angle bracket writing <>

Because <> in ts may also represent a generic type in addition to type assertion. Therefore, it is recommended to use as writing method for type assertions.

1. Assert a union type as one of the types

//Method 1 as variable as type
let arr = [1, 2, 3]
let result = arr.find((i) => i > 2) as number
result * 7 // The determination may be data or undefined

//Method 2 Angle bracket writing <type> variable
let arr2 = [1, 2, 3]
let result2 = arr.find((i) => i > 2)
let a = <number>result2 * 7 // The determination may be data or undefined

2. Assert the parent class as a more specific subclass

3. Assert any type to any

/// 3. Assert any type as any
// Any type can access any properties and methods regardless of whether they exist or not
(Window as any).abc = '77'

(8) Type aliases and string literal types

1.Type alias

//Type alias is often used for union types
type All = number | string | boolean
let a: All = 1
a = '123'
a = true

2. String literal type

//String literal type used to specify optional strings
type Name = 'csq' | 'zkj' | 'dy'
let b: Name = 'csq'
b = 'dy'

(9) Enumeration Enum

// ====tuple====
let tarr: [number, string] = [1, '2']
// When pushing, you can add number or string type data
tarr.push(3)
tarr.push('4')

// ====Enumeration====
// Use an enumeration type to assign a name to a set of values
// You can get the value through the name, and get the name through the value.
// Enumeration members will be assigned values that increase from 0, and the enumeration value will be reversely mapped to the enumeration name.
// 1,2,3,4
enum NumberType {
    one = 2,//Manual assignment, no assignment, the first parameter defaults to 0, and then increases by one incrementally
    two = 1, //If the following value is not assigned manually, it will be incremented by one based on the previous value.
    three,
    four
}
// Note for manual assignment: try not to write some repeated values
console.log(NumberType);
// There are two types of enumeration items: constant members and calculated members
// The calculated items need to be placed before the enumeration items that have been assigned values, and the enumeration items that have not been manually assigned cannot be stored later.
enum Color {
    red,
    blue = "blue".length,
    green=11
}

//Constant enumeration is an enumeration type defined using const enum
//The difference between a constant enumeration and a normal enumeration is that it will be deleted during the compilation phase and cannot contain calculated members.
const enum Obj {
    o,
    b,
    j = 10 + 10
}
console.log(Obj.o);
console.log(Obj.b);
console.log(Obj.j);
// External enumerations (Ambient Enums) are enumeration types defined using declare enum
// The types defined by declare will only be used for compile-time checking and will be deleted from the compilation results.
// declaration file
declare const enum ABC {
    a, b, c
}
console.log(ABC.a);