javascript 中的类型检查(2)

作者: zidea | 来源:发表于2019-02-28 18:22 被阅读10次

我们无需改变 javascript 就可以切实地感受到 typescript 带来好处,

我们只要 visual studio code 中的 js 文件头部加入 //@ts-check,然后在 add 函数第一参数 a 前添加 /*@ type{number}/ 我们这时候就将 a 类型定义为 number,如果在调用时 add 我们传入字符串类型的参数就会得到相应错误提示。

//@ts-check

export function add(/**@type{number} */a,b){
    return a + b;
}


add('strng',1); //检查类型

同样我们给 printTitle 的参数 title 指定默认值为空字符串,这样也会认为类型为字符串,与上面效果相同。
动态语言 VS 静态语言

动态语言特性

  • 灵活性
  • less verbose/less ceremony 不拘泥细节和格式
  • 更多的改变空间
  • 话费在语义上时间会更少
  • 容易测试

静态语言

  • 更早进行错误检查和提示
  • 更好的编码文档
  • 有优化编译的条件
  • 可以提高运行时的效率
  • 更好开发体验

export function printTitle(title= ''){
    console.log(title);
}

printTitle(123) //提示输入字符串

javascript 和 typescript 可以友好共存

这样您就可以逐步地改造我们现有的项目,我们可以一个一个的文件进行转换为 typescript。

我们有一个简单的不能再简单 javascript 文件,我们现在要将他转换为 typescript 文件,只需要将后缀 .js 修改为 .ts 。

const tutorial = {
    title:'angularjs tutorial',
    author:'zidea'
}

class tutorialService{
    constructor(apikey){
        this.apikey = apikey
    }
}

修改后会提示我们没有指定 apikey 的类型。
屏幕快照 2019-02-24 下午12.45.33.png
const tutorial = {
    title:'angularjs tutorial',
    author:'zidea'
}

class tutorialService{
    private apikey:string
    constructor(apikey:string){
        this.apikey = apikey
  }
  • 我们需要为 apikey 指定类型
  • 然后在 class 中定义一个 apikey 字符串类型的私有变量
export default class tutorialService{
    private apikey:string
    constructor(apikey:string){
        this.apikey = apikey
    }
}

然后让我们的文件模块化,export default ,typescript 的编译器及支持 commonjs
模块管理也支持 es 的模块管理。

export interface ITutorial {
  title: string,
  author: string
};

export enum NewsSource{
    WECHAT = 'we-chat-web',
    JIANSHU = 'jianshu-web'
}

export default class tutorialService {
  private apikey: string;
  constructor(apikey: string) {
    this.apikey = apikey;
  }

  async feacthArticles(source:NewsSource):Promise<ITutorial[]> {
      return [{
            title:'angular tutorial',
            author:'zidea'
        }]
  }
}
  • 我们定义接口 ITutorial 来定义 feacthArticles 返回值的类型
  • 定义枚举 NewsSource 来限制 NewsSource 的取值范围
  • 然后修改 feacthArticles 函数来确定参数的类型和返回值的类型

相关文章

网友评论

    本文标题:javascript 中的类型检查(2)

    本文链接:https://www.haomeiwen.com/subject/anivyqtx.html