使用TS的猴儿们都知道,写TS经常会提示错误,一边写一边纠错,因为每个函数的每个参量的类型是固定的,每次用到哪个函数的时候,编辑器会自动提示这个函数的哪些参量是必须的,每个类型是啥。这个与类型相关的特点能极早的检查代码错误做到early fail。而写JS的人可能动态类型一时爽,代码一多就地雷场。发生了什么?
- 什么是动态?什么是静态?
Dynamically-typed languages perform type checking at runtime, while statically typed languages perform type checking at compile time.
简言之,一门语言在编译时报错,那么就是静态语言,如果在运行时报错,那么就是动态语言。
JS在运行时才知道错误,属于动态类型语言。
TS在编译时就会知道错误,所以它是静态类型语言。
- 强类型语言?弱类型语言?
A strongly-typed language is one in which variables are bound to specific data types, and will result in type errors if types do not match up as expected in expression——regardless of when type checking occurs.
强类型语言是一种强制类型定义的语言,即一旦某一个变量被定义类型,如果不经强制转换,那么它永远就是该数据类型。
A weakly-typed language on the other hand is a language in which variables are not bound to a specific data type; they still have a type, but type safety constraints are lower compared to strongly-typed languages.
弱类型语言是一种弱类型定义的语言,某一个变量被定义类型,该变量可以根据环境变化自动进行转换,不需要经过现行强制转换。
TS是强类型,JS是弱类型。
下面是从Wiki上借鉴来的详细版资料:
Dynamic type checking is the process of verifying the type safety of a program at runtime. Implementations of dynamically type-checked languages generally associate each runtime object with a type tag (i.e., a reference to a type)containing its type information. This runtime type information (RTTI) can also be used to implement dynamic dispatch, late binding, downcasting, reflection, and similar features.
Static typing can find type errors reliably at compile-time, which should increase the reliability of the delivered program. Static typing advocates believe programs are more reliable when they have been well type-checked, whereas dynamic-typing advocates point to distributed code that has proven reliable and to small bug databases.