首先先建一个页 Runbood.ts (Tips: 是以.ts)
然后就可以直接在里面写,会有各种写法错误时候的提示,可以直接把我写的文件复制过去 就会看到有想过的错误提示了
// 任意类型
let hht: any = 1; hht = 'I am who I am'; hht = false;
let arrayList: any[] = [1, false, 'fine'];
// 字符串的使用
let myname: string = "Runoob";
let words: string = `您好,今年是 ${ myname } 发布`;
// null 和 undefined 是没有定义这两个类型的
// boolean的使用
let flag: boolean = true;
// 数字的使用
let years: number = 5;
// 数组的使用
let arr1: number[] = [1, 2]; // 在元素类型后面加上[]
let arr2: Array<number> = [1, 2]; // 或者使用数组泛型
let arr3: [string, number];
arr3 = ['Runoob', 1]; // 运行正常
// 枚举 数组集合
enum objTS1 {a, b, c}; // 输出 { '0': 'a', '1': 'b', '2': 'c', a: 0, b: 1, c: 2 }
enum objTS2 {a=1, b=2, c=3}; // 输出 { '1': 'a', '2': 'b', '3': 'c', a: 1, b: 2, c: 3 }
let index1: objTS2 = objTS2['2'] // b
let index2: objTS2 = objTS2.b // 2
enum objTS3 {a=0, b=3, c}; // 输出 { '0': 'a', '3': 'b', '4': 'c', a: 0, b: 3, c: 4 }
// ---------------------------------拓展知识点---------------------------------
// I:类型转换的功能
var str = '1'
var strToNum:number = <number> str // Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other
var strToAnyToNum:number = <number> <any> str // 输出数字类型值为1
// II: 箭头函数的功能
const hhh = ()=>{ return '777'} // const hh = function() { return '666'}
// III: 变量作用域
class objConfig { // [Function: objConfig] { a1: 11 }
static a1 = 11
a2 = 22 // 实例变量
fun(){
var a3: number = 33; // 局部变量
return 44
}
}
console.log(objConfig.prototype) // objConfig { fun: [Function] }
console.log(objConfig.prototype.fun()) // 44
console.log(objConfig.prototype.fun.a3) // ????? 如何获取到33的值呢
let objSLH = new objConfig(); // SLH 实例化
console.log(objSLH) // objConfig { a2: 22 }
// ---------------------------------跟之前js的写法完全一样的知识点---------------------------------
// @1 条件语句
// @2 运算符
// @3 循环
// ---------------------------------各种可能会报错的合集--(原因:TypeScript 遵循强类型,如果将不同的类型赋值给变量会编译错误)-------------------------------
let hh1: boolean = 1; // 报错 Type '1' is not assignable to type 'boolean'
let hh2: [string, number];
hh2 = [1, 'Runoob']; // 报错 Type 'number' is not assignable to type 'string' 和 Type 'string' is not assignable to type 'number'
var defaultNum = 2; // 类型推断为 number (已经定义过的重新赋值)(Tips: 如果由于缺乏声明而不能推断出类型,那么它的类型被视作默认的动态 any 类型)
defaultNum = "12"; // Type '"12"' is not assignable to type 'number'