即非原始类型,如 对象、数组、函数 等

  1. const foo: object = {}
  2. const bar: object = [];
  3. const baz: object = function() {}

注意 object 不单指普通的对象,需求普通对象类型,要使用类似对象自变量的语法

const obj: { foo: number, bar: string } = { foo: 123, bar: 'string' }

在 TypeScript 中要限制对象类型应该使用 接口

数组类型

const arr1: Array<number> = [1, 2, 3];
const arr2: number[] = [1, 2, 3];

元级类型 Tuple

const tuple: [number, string] = [18, 'ziee'];  
// 使用数组下标的方式来获取
const age = tuple[0]; const name = tuple[1];  
// 解构获取 
const [age, name] = tuple;

枚举类型 Enum

enum PostStatus {
    Draft = 0,
  Unpublished = 1,
  Published = 2
}

const post = {
    title: 'Hello TypeScript',
  content: 'TypeScript is a typed superset of JavaScript.',
  status: PostStatus.Draft
}

数字枚举

  • 可不用赋值,默认由 0 开始
  • 赋值后,后面值的由赋值位 +1 继续下去

字符串枚举

  • 必须赋值

枚举会入侵编译后的代码,生成双向的键值对对象

var PostStatus:
(function(PostStatus){
    PostStatus[PostStatus['Draft'] = 0] = "Draft";
  PostStatus[PostStatus['Unpublished'] = 1] = "Unpublished";
  PostStatus[PostStatus['Publised'] = 2] = "Publised";
})(PostStatus || (PostStatus = {}));

常量枚举则不会在编译后生成双向键值对对象
在 enum 前加上 const

const enum PostStatus {
    Draft = 0,
  Unpublished = 1,
  Published = 2
}

函数类型

函数声明

function fun1(a: number, b: number): string {
    return 'func1';
}

// 可选参数 加上 ?:
function fun2(a: number, b?: number): string {
    return 'func2';
}

// 参数默认值
function fun3(a: number, b: number = 10): string {
    return 'func3';
}

// 可选参数与参数默认值都应该在参数列表的最后

// 对接收任意个参数,使用 rest 操作符
function fun4(a: number, b: number, ...rest: number[]): string {
    return 'func4';
}

函数表达式

const func: (x: number, y: number) => string = function (a: number, b: number): string {
    return 'func2';
}

任意类型

const a:any = 'string';