TypeScript-基本类型

139 阅读1分钟

类型定义

JavaScript 定义了 8 种内置类型:

类型描述
Number一个双精度 IEEE 754 浮点数。
String一个不可变的 UTF-16 字符串。
BigInt任意精度格式的整数。
Booleantrue和false。
Symbol通常用作键的唯一值。
Nullnull
Undefinedundefined
Object对象
Functionfunciton 函数

TypeScript 为内置类型提供了相应的原始类型:

  • number
  • string
  • bigint
  • boolean
  • symbol
  • null
  • undefined
  • object
其他重要的 TypeScript 类型
类型描述
unknownthe top type.
neverthe bottom type.
object literal对象定义 eg { property: Type }
void类型返回undefined
T[]泛型 Array<T>
[T, T]元组,它们是固定长度但可变的
(t: T) => U定义函数

认识基础常用的类型定义

string

const testName: string = '李四';

number

const age: number = 23;

boolean

const isShow: boolean = true || false;

null和undef

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

Typescript中undefined与null的区别

array

let arr1:string[] = ['q','w','e']
let arr2:Array<number> = [1,2,3]

object

function printCoord(pt: { x: number; y: number }) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });

function

函数参数的类型定义

function greet(name: string) {
  console.log("Hello, " + name.toUpperCase() + "!!");
}

greet('12')

函数返回值类型的定义

function getFavoriteNumber(): number {
  return 26;
}

getFavoriteNumber()

总结

列举了经常使用的基本类型的示例。还有一些其他的类型定义,例如对object而言,它的属性是可选的、接口的定义、type的定义。等。还需要在一篇展开。