基本类型
-
布尔值
boolean
-
数字
number
-
字符串
string
-
数组
- 元素类型后面接上 []
number[]
- 使用数组泛型
Array<number>
- 只读数组
ReadonlyArray<T>
- 元素类型后面接上 []
-
元组:
[string, number]
表示一个已知元素数量和类型的数组,各元素的类型不必相同
-
枚举:
enum
类型是对JavaScript标准数据类型的一个补充。- 为提高性能在定义时可加上
const
- 相对于json的优点:可以通过值映射到名字
enum Color {Red = 1, Green, Blue} let colorName: string = Color[2]; console.log(colorName); // 显示'Green'因为上面代码里它的值是2
- 为提高性能在定义时可加上
-
object
-
any: 任意类型
-
void: 表示没有任何类型,只能为它赋予
undefined
和null
-
Null 和 Undefined
-
never:
never
类型表示的是那些永不存在的值的类型。
// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
throw new Error(message);
}
// 推断的返回值类型为never
function fail() {
return error("Something failed");
}
// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
while (true) {
}
}
类型断言
类似其它语言里的类型转换
- 使用
as
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
- 使用
<>
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
接口
interface
interface LabelledValue {
label: string;
}
- 只读属性:
readonly
interface Point {
readonly x: number;
readonly y: number;
}
- 函数类型
interface SearchFunc {
(source: string, subString: string): boolean;
}
const mySearch: SearchFunc = function(src, sub) {
let result = src.search(sub);
return result > -1;
}
- 可索引的类型
interface LabelledValue {
[label: string]: number;
}
- 继承接口:
extends
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
泛型
- 泛型接口
interface GenericIdentityFn<T> {
(arg: T): T;
}
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: GenericIdentityFn<number> = identity;
高级类型
- 交叉类型
&
- 联合类型
|
- 类型别名
- 与接口区别:
- 可以作用于原始值,联合类型,元组以及其它任何你需要手写的类型
- 继承使用
&
type Name = string; type NameResolver = () => string; type NameOrResolver = Name | NameResolver; function getName(n: NameOrResolver): Name { if (typeof n === 'string') { return n; } else { return n(); } }
- 与接口区别: