Last updated on Oct 2, 2022

原始类型

对于 JavaScript 的内置原始类型(Primitive),在 TypeScript 中它们都有对应的类型注解:

const name: string = 'Samuel'
const age: number = 24
const male: boolean = false
const undef: undefined = undefined
const nul: null = null
const bigintVar1: bigint = 9007199254740991n
const bigintVar2: bigint = BigInt(9007199254740991)
const symbolVar: symbol = Symbol('unique')
const obj: object = { name, age, male }

null 与 undefined

在 JavaScript 中,null 与 undefined 分别表示「这有个值,但是个空值」

和「为初始化 or 不存在」。

而在 TypeScript 中,这两个值都是有具体意义的类型

在没有开启 strictNullChecks 时,默认 nullundefined 都可以分配给任何其他类型(即视作其他类型的子类型)。例如 string 类型会被认为包含了 nullundefined 类型。

const tmp1: null = null
const tmp2: undefined = undefined

// 以下仅在关闭 strictNullChecks 时成立
const tmp3: string = null
const tmp4: string = undefined

void

在 JavaScript 中的 void

<a href="javascript:void(0)">清除缓存</a>

这里的 void(0) 等价于 void 0,即 void expression 的语法。

void 操作符会执行后面跟着的表达式并返回一个 undefined,例如

void 0

void function iife() {
  console.log('invoked')
}()

void((function iife(){})())

本质上是因为 void 操作符强制将后面的函数声明转化为了表达式,等价于 void((function iife(){})())

而在 TypeScript 的原始类型标注中也有 void,与 JavaScript 中不同的是,这里的 void 用于描述一个内部没有 return 语句,或者没有显式 return 一个值的函数的返回值

// 隐式推导为:function func1(): void
function func1() {}

// 隐式推导为:function func2(): void
function func2() { return }

// 显式返回了 undefined,根据该返回值类型被推导为 undefined
// function func3(): undefined
function func3() { return undefined }

// 显式返回了 null,根据该返回值类型被推导为 null
// function func4(): null
function func4() { return null }