类型定义
JavaScript 定义了 8 种内置类型:
| 类型 | 描述 |
|---|---|
| Number | 一个双精度 IEEE 754 浮点数。 |
| String | 一个不可变的 UTF-16 字符串。 |
| BigInt | 任意精度格式的整数。 |
| Boolean | true和false。 |
| Symbol | 通常用作键的唯一值。 |
| Null | null |
| Undefined | undefined |
| Object | 对象 |
| Function | funciton 函数 |
TypeScript 为内置类型提供了相应的原始类型:
numberstringbigintbooleansymbolnullundefinedobject
其他重要的 TypeScript 类型
| 类型 | 描述 |
|---|---|
unknown | the top type. |
never | the 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
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的定义。等。还需要在一篇展开。