类型分类
1.基础类型(primitive type)
-
string
类似: "Hello, world"
-
number
类似:42, 48.5, 同js的typeof一样,都返回 'number',不区分整形和浮点型,统一为number类型。
-
boolean
只有两个值: true 和 false.
-
bigint
有两种形式:
- 数字后面加n, 例如 123n表示bigint.
- 构造函数BigInt(123),这两种方式构造的BigInt相等。 什么时候用BitInt.
- 你使用的值超过了
Number.MAX_SAFE_INTEGER
- 计算精度大于速度。
-
undefined 和 null
这两个类型比较简单,值只有一个。
const foo:undefined = undefined;
const bar:null = null;
-
symbol
用构造函数Symbol创建一个全局唯一的值, 类型为symbol, 值为Symbol("name");
const firstName = Symbol("name");
const secondName = Symbol("name");
2.Object类型
非原始类型(non-primitive type). 是一种数据封装的手段,如interface, type, class的实例都是object类型,如以下的person, point, person2.
class Point {
x!: number;
y!: number;
}
let point: Point = { x: 1, y: 2 };
type Person = {
name: string;
age: number;
};
let person:Person = {
name: "TK",
age: 24,
}
let person2: { name: string; age: number } = {
name: "TK2",
age: 25,
};
3.function类型
函数是 JavaScript 中传递数据的主要方式,TS中允许指定参数和返回值的类型。形如:
// Parameter type annotation
function greet(name: string) {
console.log("Hello, " + name.toUpperCase() + "!!");
}
function的其他形式如:
class Person {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
Person'type is function.