美文网首页
TypeScript学习笔记(第三课,类型推论)

TypeScript学习笔记(第三课,类型推论)

作者: LongFor_ | 来源:发表于2019-11-13 15:21 被阅读0次

什么是类型推论


下面的代码虽然没有指定类型,但是会在编译的时候报错:

let study = '学习'

study = 666

//  Type '666' is not assignable to type 'string'.

这两句代码在我们看来其实是没有什么错误的,但是在TS中它会进行类型推论。实际上,这两句代码等价于:

let study:string = '学习'

study = 666

 // Type '666' is not assignable to type 'string'.


简单来说,TypeScript 会在没有明确的指定类型的时候推测出一个类型,而推测的依据其实就是后面赋的值是什么类型的。这就是TypeScript类型推论。

*** 另外一种特殊的情况,如果在定义某个变量的时候没有赋值,然后之后不论有没有进行赋值操作,该变量都会被推断为any类型而不被类型检查 。***


let study

study = '学习'

study = 666

study = true

study = null

study = undefined

相关文章

网友评论

      本文标题:TypeScript学习笔记(第三课,类型推论)

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