类型注解和类型推断

一、类型注解

type annotation ,类型注解,通过类型注解告诉TS变量是什么类型

二、类型推断

TS会尝试分析变量的类型,如果TS能够自动分析变量类型,我们就什么都不需要做了,如果TS无法分析变量类型的话,我们就需要使用类型注解。

const str1= 'a'; const str2 = 'b';  const str3 = str1 + str2; 针对str1、str2和str3这种原始数据类型常量, TS能够自动分析变量类型。

function sumFn (a: number, b:number) {

  return a + b

}

const sum = sumFn(1, 2) // TS没有办法判断函数参数可能是什么类型,需要通过类型注解的方式主动告诉TS参数的具体类型

原文地址:https://www.cnblogs.com/xldxh/p/15468392.html