Skip to content

Latest commit

 

History

History
54 lines (40 loc) · 1.95 KB

为什么需要类型.md

File metadata and controls

54 lines (40 loc) · 1.95 KB

在一个多人协作的大型项目中,小明作为基础库的研发工程师,提供了一个公共函数调用 showInput(input),定义如下:

function showInput(input) {
  return input.show();
}

此时,作为业务调用方的小红,在业务代码中作出调用:

// 在javascript中调用报错
// Uncaught TypeError: input.show is not a function
showInput("hello world");

看过前面的函数定义,我们知道以上代码不出意外会报错,因为 hello world字符串没有show方法

现实情况中,showInput(input) 可能是我们可以了解的此API的所有外形描述。函数定义对于调用者而言是一个黑盒,错误的调用成为了大概率事件,可怕的是开发阶段你完全觉察不到错误的存在,把存在错误的代码发布到生产环境,可能会导致业务损失。

为了解决这个问题,我们用typescript为 input 参数提供了类型描述 InputType

// InputType描述了一个包含show方法的类型
type InputType = {
  show: ()=>void;
};
showInput(input: InputType);

当你用同样的方式在 typescript 中调用时 showInput("hello world"),在代码没有发布之前,编译器就会提示你存在错误

// 以下代码在typescript中调用报错
// error TS2345: Argument of type '"hello world"' is not assignable to parameter of type 'InputType'.
showInput("hello world");

在支持typescript语言的编辑器(如vscode)中,InputType 类型甚至会在编码阶段就被正确的智能提示出来,改成正确版本:

// 定义input变量,包含show方法
const input = {
  show(){
    return "hello world"
  }
}
// 将包含show的变量传递给函数
showInput(input);

这是到目前为止,这是JavaScript需要强制类型的最好理由,它可以让绝大部分的错误发生在编码阶段,而不是让错误发生在线上