Skip to content
On this page

JS 有哪些数据类型

null、undefined、string、number、boolean、bigint、symbol、object (包含 Array、Function、Date、RegExp)

TS 有哪些数据类型(datatype)

JS 有的 TS 也都有,另外还要加上 void、never、enum、unknown、any,再加上 自定义类型 type、inferface 。

如何在 TS 里描述对象的数据类型(datatype)

  • 用 class / constructor 描述
  • 用 type 或 interface 描述

一般对象(Object)包含数组对象、函数对象、正则对象、日期对象等等,Object 是一个比较大范围的数据类型,一般在 TS 中不用 Object。 用索引签名(index signature)和 Record 描述普通对象:

ts
type P = {
	weight: number,
	[k: string]: number
}
const A: P = {
	weight: 120,
	age: 18
}
// A 表示 k 为 string 、value 为 number 的所有对象
// k 的类型可以不是 string 吗?可以为 number、symbol

type R = Record<string, number>
const B: R = {
	age: 18,
	weight: 120
}

type O = {
	name: string,
	age: number
}
const C: O = {
	name: 'he',
	age: 18
}

用 [] 和 Array 泛型描述数组

开发者一般使用 Array<T> 或 string[] 或 [string, number]

ts
type A = string[]
const a: A = ['h', 'e'] // 等价于 type A = Array<string>

type B = number[]
const b: B = [1, 2] // 等价于 type B = Array<number>

type C = [string, number] // 二元组
const c: C = ['he', 18] // 使用情况看下图(三元组)有报错

type D = [string[], number[){data-zoomable}
const d: D = [['he', 'llo'], [18, 22){data-zoomable}

思考题:

ts
type A = [1, 2, 3] // 下面怎么写?
// const a: A = ?
const a: A = [1, 2, 3] // 只能这么写了

如何描述函数对象

ts
type FnA = (a: number, b: number) => number
type FnB = (a: string, b: string) => string

type FnReturnVoid = (s: string) => void
type FnReturnUndefined = (s: string) => undefined
const v: FnReturnVoid = (s: string) => { 
	console.log(s)
}
const u: FnReturnUndefined = (s: string) => {
	console.log(s)
	return undefined
}

type Person = {name: string, age: number}
type FnWithThis = (this: Person, name: string) => void
const sayHi: FnWithThis = function(name){ console.log("hi" + this.name) }
sayHi("Jack")
// The 'this' context of type 'void'
// is not assignable to method's 'this!
// of type 'person'.
// 为什么?

由于 Function 不精确,所以一般使用 () => ? 来描述函数,其他对象一般使用 class 描述。

Released under the MIT License.