TS Learning 01 - Basic Data Types

basic type

array

  • The first: element type []
let arr: number[] = [1,2,3]
  • The second type: Array generics -Array<element type>
let arr: Array<number> = [1,2,3]

Tuple

Represents an array of known number and type of elements

let arr: [string, number]
a = ['RenNing', 18]

When accessing out-of-bounds elements, the union type will be used instead

arr[1] //18
arr[3] = 'world' // (string | number) 类型

Enumeration enum

An addition to JavaScriptthe standard data types.

enum Color {
    
    Red, Green, Blue}
let c: Color = Color.Green //1

By default, elements are numbered starting from 0 ; member values ​​can be manually specified

enum Color{
    
    Red = 3, Green, Blue = 8}
let c: Color = Color.Green //4

Channel his name through the value of the enum

let colorName: string = Color[3] //red

Any

Void

voidType is like anythe opposite of type, it means there is no type at all.

When a function does not return a value, you usually see that its return type isvoid

Declaring a voidvariable of a type is not very useful because you can only assign undefinedandnull

Null and Undefined

let u: undefined = undefined;
let n: null = null;

By default nulland undefinedare subtypes of all types.

nulland can be undefinedassigned to numbervariables of type.

let a:number = null

When you specify --strictNullChecksflags, nulland undefinedcan only be assigned to voidand their respective

somewhere you want to pass in an stringor nullor undefined, you can use the union typestring | null | undefined

Never type

Identifies the type of a value that never exists

For example, neverthe type is the return type of a function expression or an arrow function expression that always throws an exception or never returns a value at all;

neverA type is a subtype of, and is assignable to, any type; however, no type is nevera subtype of, or is assignable to, nevera type

function error(message: string) :never {
    
    
    throw new Error(message)
}

type assertion

Form 1: "angle brackets" syntax

let someValue: any = 'this.is a string'
let strLength: number = (<string>someValue).length

Form 2: as syntax

let strLength: number = (someValue as string).length;

Guess you like

Origin blog.csdn.net/weixin_46211267/article/details/131937818