const message = "Hello World"
message.toLowerCase(); // 得到“hello world”
message(); // 报错:TypeError:message is not a funtion
function fn(x) {
return x.flip();
}
// 可知,要成功执行上面函数内容代码是要满足一定条件的,那就是 x 必须能够调用 flip() 方法;
JavaScript 只能在运行时发现错误!
像 TypeScript 等类型检查工具,可以做到在代码运行之前发现错误!
const message = "hello world!"
message()
const user = {
name: "大哥",
age: 25
}
console.log(user.location)
const user = {
name: "大哥",
age: 25
}
console.log(user.location)
const user = {
name: "大哥",
age: 25
}
console.log(user.nam)
let say = () => {
return 1
}
say + 1 // 报错
say() + 1 // 正常
const value = Math.random() < 100 ? 'a' : 'b'
if (value !== 'a') {
} else if (value === 'b') { // 报错!
}
这里省略了,网上有很多相关教程!
https://www.visualstudio.com/Download
https://nodejs.org/en/download
npm install -g typescript
console.log("Hello TS!")
tsc .\hello.ts
得到了预想的结果!
function say(name, age) {
console.log(`my name is ${name}, I am ${age} years old!`)
}
say("訾博", 25)
function say(name, age) {
console.log("my name is ".concat(name, ", I am ").concat(age, " years old!"));
}
say("訾博", 25);
tsc --init # 生成配置文件
参数报错问题暂且放置,我们暂时先关闭严格模式!
tsc --watch
此时即实现了,当 ts 文件报错的时候,自动编译成对应的 js 文件,即 js 文件随着 ts 文件的保存而与 ts 文件保持同步!
ts 报错的时候,可以正常编译成 js 文件,并可以运行!我们想当 ts 报错的时候不生成 js 文件,加上 -noEmitOnError 参数!
tsc -noEmitOnError hello.ts
function say(name, age) {
console.log(`my name is ${name}, I am ${age} years old!`)
}
say("訾博")
function say(name, age) {
console.log(`my name is ${name}, I am ${age} years old!`);
}
say("訾博");
使得 ts 报错时不生成 js 文件!(提前把之前编译的 js 文件删除!)
并非一定要显式定义类型!
// 类型推断
let message = "hello ts!"
message = "hello world!"
message = 100 // 报错:不能将类型“number”分配给类型“string”。
**并非所有的浏览器都兼容 ES6 语法!**我们需要”降级编译“!
不过,大多数浏览器都已经支持 ES6 了!ES2015 就是 ES6!
测试完之后,我把 target 恢复到了默认的 es2016 ,即 ES7!
tsconfig.json 文件:新开发的项目应该全部打开这些严格性检查!
/* Type Checking */
"strict": true, // 严格模式
"noImplicitAny": true, // 禁止隐式类型为 any
"strictNullChecks": true // 开启 null 和 undefined 的检查
做项目迁移时这么做!一般不这么做!
关闭严格模式,类型隐式推断为 any 类型,也就回到了普通的 js 代码的效果了,与是否使用 ts 无区别!我们可以 strict
严格模式,我们呢也可以将 noImplicitAny
设置为 true
。
参考文章:segmentfault.com/a/119000001…
禁止隐式 any 类型!
**建议开启!**开启之后如严格模式一样,没有声明类型的变量会报“……隐式具有 any 类型”的错误!
是否开启 null 和 undefined 的检查!
此时未开启严格模式!开启了
noImplicitAny
!
关闭下面两个,开启严格模式也能达到同样的效果!