Skip to content

枚举和断言

枚举

枚举编号默认从 0 开始

ts
enum SexType {
  BOY,
  GIRL,
}
console.log(SexType.BOY) // 0
console.log(SexType.GIRL) // 1

枚举编号会自动递增

ts
enum SexType {
  BOY = 2,
  GIRL,
}
console.log(SexType.BOY) // 2
console.log(SexType.GIRL) // 3

枚举可以自定义

ts
enum SexType {
  BOY = '',
  GIRL = '',
}
console.log(SexType.BOY) // 男
console.log(SexType.GIRL) // 女

断言

语法: as 指定类型

as const 断言

根据转换对应类型

ts
const b: 'whbbit' = 'whbbit'
// 类型等价于
const c = 'whbbit'
// or
const d = 'whbbit' as const // 类型断言为whbbit

数组 as const 会转换为元组

ts
const a = 'whbbit'
const b = 20
const _arr = [a, b] // 类型为(string|number)[]

const arr1 = [a, b] as const // 转换为元组,类型为[string, number]
const arr2 = <const>[a, b] // 转换为元组,类型为[string, number]

对象 as const

值为常量时,类型为对应的值,为变量时类型为对应的值类型

ts
const a = 'whbbit'
const b = 170 as const
const obj = {
  name: 'whbbit',
  age: 23,
  nick_name: a,
  b,
} as const
// 对应的类型为
// const obj: {
//   readonly name: string
//   readonly age: number
//   readonly nick_name: 'whbbit'
//   readonly b: 170
// }

在解构中使用

ts
function test1() {
  const a = 'whbbit'
  const b = (x: number, y: number): number => x + y
  return [a, b]
}
// test1 类型为 function test1():(string | ((x:number, y:number)=>number))[]

// 使用断言
function test2() {
  const a = 'whbbit'
  const b = (x: number, y: number): number => x + y
  return [a, b] as [typeof a, typeof b]
}
// test2的类型为 function test2(): readonly [string, (x: number, y: number) => number]

function test3() {
  const a = 'whbbit'
  const b = (x: number, y: number): number => x + y
  return [a, b] as const
}
// test3的类型为 function test3(): readonly [string, (x: number, y: number) => number]

非空断言

设定一个类型后默认可以重新赋值为 null/undefined

ts
let name: string = 'whbbit'
name = null
name = undefined

如果不希望可以重新赋值为 null/undefined 需要在 tsconfig.json 文件中将 "strictNullChecks": true 开启

ts
let name: string = 'whbbit'
name = null // 报错
name = undefined // 报错

dom 操作

操作 dom 时,可以断言为对应的 html 元素来获取更好的提示

ts
const el = document.querySelector('.hd') as HTMLDivElement
// or 使用!断言为非空
const element = document.querySelector('.hd')!

事件处理

ts
const button = document.querySelector('#button') as HTMLBodyElement

button.addEventListener('click', (e: Event) => {
  e.preventDefault()
})