TS 类型列表
number、string、boolean
IDE 使用 Webstorm,新建一个 basis.ts
//声明一个变量 a,同时指定类型为 number,注意是小写
let a: number;
// a 的类型设置为 number,在以后使用过程中 a 的值只能是数字
a = 10;
a = 33.11;
//a='hello';//会报错,因为变量 a 类型是 number,不能赋值字符串
let b: string;
b = 'hello';
//b = 123;
//声明完变量直接赋值
let c: boolean = false;
//如果变量的声明和赋值是同时进行的,TS可以自动对变量进行类型检测
let d = false;
//JS中的函数是不考虑参数的类型和个数的
/*function sum(a,b){return a+b;
}
console.log(sum(123,456));//579
console.log(sum(123,"456"));//123456
*/
//方法参数可以声明类型,方法返回值也可以声明类型
function sum(a: number, b: number):number {return a + b;
}
console.log(sum(123,456));
//记住,在字符串前添加 + 号,可以将string转为number(字符串内容为数字才有意义)
console.log(1+ +'1')//输出2
在 Webstorm 的 terminal 运行 tsc basis.ts
是报错了:tsc : 无法加载文件 C:\Users\00lix\AppData\Roaming\npm\tsc.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅 https:/go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies
完整报错如下: <img src=“https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/e53134e9314a45dc9f960f12f3d979ab~tplv-k3u1fbpfcp-zoom-in-crop-mark:4536:0:0:0.image) 解决办法: 以管理员身份运行powershell执行 set-ExecutionPolicy RemoteSigned
,选择 Y 或者 A 即可 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fkIwOpp8-1660788289599)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b9671d18d15d48bf903e3fd2b201dc90~tplv-k3u1fbpfcp-zoom-in-crop-mark:4536:0:0:0.image)] 再次执行 tsc basis.ts
即可编译完” style=“margin: auto” />