TS基础类型

2023-11-07  本文已影响0人  Jason_Fight

1. Boolean

const flag: boolean = true;

2. Number

const nunm: number = 123;

3. String

const str: string = 'hello'
```ts
#### 4. null
```ts
let nulltype: null = null

5. Undefined

let UndefinedType: undefined = undefined

6. Enum

通过枚举可定义一些带名字的常量,可以清晰的表达意图或者床见椅子有区别的用例,

6.1 普通枚举
enum Color {
  RED,
  BULE,
  YELLOW
}
const red: Color = Color.RED;
const yellow: Color = Color.YELLOW;
console.log(red); // 0
console.log(yellow); // 2

3 6.2 设置初始值的枚举

enum Color_1 {
  RED =  5,
  BLUE,
  YELLOW  = 9
}

const red_1: Color_1 = Color_1.RED;
const yellow_1: Color_1 = Color_1.YELLOW;
console.log(red_1); // 5
console.log(yellow_1); // 9
6.3 字符串枚举
enum Color_2 {
  RED = 'red',
  BLUE = 'blue',
  YELLOW = 'yellow'
}
const red_2: Color_2 = Color_2.RED
const blue_2: Color_2 = Color_2.BLUE
console.log(red_2); // red
console.log(blue_2); /// blue

7. Array

数组的两种定义形式

const arr: number[] = [1, 2, 3]
const arr_1: Array<number> = [1, 2, 3]

8. tuple

元组的长度和每一个位置的变量类型是指定的.

const tuple_1: [string, number, boolean] = [ 'abc', 123, true]

9. any

let anyType: any = 1
anyType = '123'
anyType = true

10. void

void 意思就是无效的, 一般用于没有返回值的函数中

function sayHello(): void {
  console.log('hello');
}

11. never

never 类型表示用不存在的值的类型,例如总会抛出异常或根本不会有返回值的函数值永不会存在的两种情况

抛出异常

function errorFun(msg: string): never {
  throw new Error(msg)
}

存在死循环

function foreverFun(): never {
  while(true){}
}

12. Unkmown

unknown与any一样,所有类型都可以分配给unknown:

let unkonwValue: unknown = 1;
unkonwValue = 'string'
unkonwValue = false

unkown 与 any 的区别
任何类型的值可以赋值给any,同时any类型的值也可以赋值给任何类型。unknown 任何类型的值都可以赋值给它,但它只能赋值给unknown和any

上一篇 下一篇

猜你喜欢

热点阅读