TypeScript学习笔记(二):函数类型注解

336 阅读2分钟

参数类型注解

// 原始类型注解
function demo(x: string) {}

// 内联方式注解
function demo(x: {name: string}) {}

//接口方式注解
interface IUser {
	name: string
}
function demo(x: IUser) {}

返回类型注解

// 内联方式注解
function demo(x: string): {title: string...}

同样,返回值类型也可以使用其他如接口等方式注解

void

void表示函数没有返回值。

一般不需要注解返回值,TypeScript会自动推断。但有时这会导致一些错误运行时才被发现,所以最好除了void类型的返回值,都加上注解。

可选参数

TypeScript中,‘?’号表示可选。我们可以在参数后面加上?号表示这是个可选参数:

function demo(x: string, y?: number) : any {}

同时,于ES6一样,我们也可以在函数定义时指定可选参数的默认值:

function demo(x: string, y: number = 0) : any {}

指定了默认值的可选参数,在注解时不需要再加上?号。

重载

TypeScript支持函数重载的声明。这些声明只是用于记录函数允许运行的方式,不会增加任何运行时开销。同时,重载声明的真正实现函数(一般是最后一个声明)需进行类型判断。示例如下:

function demo(x: string);
function demo(x: string, y: number);
function demo(x: string, y?: number, z?: boolean) {
	// 需要判断参数个数
    if (y && z) {
    	// do sth
    } else if (y) {
    	// do sth
    } else {
    	// do sth
    }
}

函数声明

在没有提供函数实现的情况下,有两种方式声明函数类型:

type LongHand {
	(a: number): number
}

type ShotHand = (a: number) => number

这两种声明方式完全相同。当你需要使用函数重载时,只能使用第一种声明方式:

type OverloadDeclaration {
	(a: number): number;
    (a: string): string;
}

类型别名和接口方式都是被允许的,如上例还可以用接口方式进行声明:

interface OverloadDeclaration {
  (a: number): number;
  (a: string): string;
}

const fn: OverloadDeclaration = (a) => {
	// ...
}

可实例化

可实例化是函数的一种特殊情况,它使用new作为前缀,意味着你必须使用new去调用它。

interface Newable {
    new (...props: any[]): any
}

class NewSth {
    constructor(...props: any[]) {
        // init instance
    }
}
const createSthFactory = (SomeConstruct: Newable, ...args: any[]) => {
    return new SomeConstruct(...args);
}

createSthFactory(NewSth, 1, 2)