经过一个小案例了解 TypeScript 函数重载和类型保护

一个小需求

  • 咱们想作一个这样的函数
    • 参数 number 默认值为 1
    • number 只能输入 1,2,3 三种类型

一、开始筹划

  • code
// 声明一个 number 的特殊类型,限制参数
type numberType = 0 | 1 | 2;

function test(a:numberType = 1){
    console.log(a)
}

test();
// 1

test(2);
// 2
复制代码

什么是联合类型?

  • 认识和复习一下联合类型
  • 联合类型表示一个值能够是几种类型之一。 咱们用竖线(|)分隔每一个类型,因此number | string | boolean表示一个值能够是number,string,或boolean。

二、使用函数重载

function test(a?: numberType):number; function test(a = 1):number | void {
    console.log(a)
}

test();
// 1

test(2)
// 2
复制代码

函数重载的几个常见问题?

  • 所谓函数重载就是同一个函数,根据传递的参数不一样,会有不一样的表现形式。

JavaScript 模拟实现css

function test(){ 
  if(arguments.length==0){ 
    console.log(a)("alert!");  
  } 
  else if(arguments.length==1){ 
    console.log(a)(arguments[0]) 
  } 
} 

test(); 
// alert!

test(2);
// 2
复制代码
  • 为何我会获得 Supplied parameters do not match any signature 的错误?(因为 JavaScript 没有函数重载)html

  • 函数实现签名,它并非重载的一部分:git

function createLog(message: string): number; function createLog(source: string, message?: string): number {
  return 0;
}

createLog('message'); // OK
createLog('source', 'message'); // ERROR: Supplied parameters do not match any signature

复制代码
  • 当至少具备一个函数重载的签名时,只有重载是可见的。最后一个声明签名(也能够被称为签名的实现)对签名的形状并无贡献,所以,要得到所需的行为,你须要添加额外的重载:
function createLog(message: string): number;
function createLog(source: string, message: string): number;
function createLog(source: string, message?: string): number {
  return 0;
}
复制代码

三、或许可使用类型保护

function isNumberType(type: number | numberType): type is numberType {
    return (number as numberType) !== undedined;
}

function test(number = 1){
    if(isNumberType(number)){
        console.log(number)
    }else{
        // 咱们作更多的类型保护能够在格式错误的时候手动作一些用户提示的操做。
        console.error('error number!')
    }
}

test(1);
// 1
复制代码

上面的类型保护的确看起来很臃肿,不过咱们能作更多的事情。具体的类型保护官网文档讲得很清楚,你们能够再温习一下。github

参考

相关文章
相关标签/搜索