TypeScript是具有类型语法的JavaScript。
是JavaScript超集,可以编译为纯JavaScript,构建安全可靠的代码,进行类似 babel 的转换。
一种基于JavaScript的强类型、静态的编程语言,提供了类型检测的工具。
特性:
-
易读
-
开源
-
提供代码的错误检测。
// @ts-check adding this to a js file shows errors in your editor
function test(arr){
if(a.length > 10)
cannot find name 'a'. // the param is arr, not a !
return arr.trim(0,10)
return arr
}
-
和JavaScript兼容性好,兼容 es6等。
// TypeScript code
type Result = 'a' | 'b'
function test(result: Result) {
if (result === 'a'){
console.log('a')
} else {
console.log('b')
}
}
// 去掉 typescript 类型声明 types are removed
// 变成 JavaScript code
function test(result) {
if (result === 'a'){
console.log('a')
} else {
console.log('b')
}
}
-
提供可靠类型,规范函数入参和出参。
// 接口 interface
interface A {
id: number
name: string
sort: 1
}
function test(user: A) {
console.log(user.id)
}
// 类型声明 type
type R = 'a' | 'b'
function test(r: R) {
if (r === 'a') {
console.log('a')
} else {
console.log('b')
}
}
为什么需要TypeScript,除了上面特性,还可以从编程语言来说:
按数据类型分
在确定变量类型的时机来区分:
1、typescript 静态类型语言: 在编译代码时能确定变量类型
- 代码可读性
- 基于类型编程,关注系统如何构建,模块之间的关联
- 编写清晰的代码
- 适合大型,复杂的项目
- 可靠,易重构。
2、JavaScript 动态类型语言: 在运行代码时能确定变量类型
- 编程自由
- 写时非常爽,重构火葬场
- 重构时工作效率
- 重构时成本增加
- 不适合大型项目代码
Typescript 缺点
- 引入太多的新概念,类型泛型、枚举等,渐进式,学会语法就能用。
- 不适合小项目,会增加开发成本,需要在项目中声明很多的类型等。