创建test.ts=>终端运行tsc test.ts=>将ts编译成js,将js文件引入Html中就OK啦。
var hello: string = "Hello World!"
console.log(hello);
类型:
布尔值: let isDone: boolean = false;
数字: let de: number = 6;
字符串: let name: string = ‘bob’;
模板字符串: let name: string =Gene
; let sentence: string =hello,My name is ${ name }
;
- 数组
let x: [string, number];
x = ['hello', 10];
//除第一个意外
console.log(x[0].substring(1));//ello
- 枚举(enum)
一元运算符==常数枚举表达式+, -, ~;
常数枚举 在enum前使用const修饰符
enum Direction {
Up = 1,
Down,
Left,
Right
}
enum Color { Red, Green, Blue };
let c: Color = Color.Green;
console.log(c) //1
//默认第一个为0
//手动赋值
enum UFO { Y = 1, B, C };
enum ASD { A = 1, S, D };
let b: UFO = UFO.B;
let a: string = ASD[2];
console.log(b) //2
console.log(a) //s
- 任意值
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;
console.log('任意值')
console.log(notSure)//false
- 空值
function warnUser(): void {
console.log('空值')
console.log('This is my warning message');
}
let unusable: void = undefined;
console.log(unusable)//undefined
- 类型断言:<>写法;as写法
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
let strLength: number = (someValue as string).length;
console.log(strLength)//16
变量声明: let var const
解构数组;对象解构;属性重命名;默认值;函数声明;解构基础上;
- 解构数组
let [first, ...rest] = [1, 2, 3, 4];
console.log(first); //1
console.log(rest); // [2, 3, 4]
- 对象解构
let o = {
n: "foo",
b: 12,
c: "bar"
};
let { n, ...passthrough } = o;
let total = passthrough.b + passthrough.c.length;
console.log(total)//15
- 展开: 对象,数组都可
let Q = [1, 2];
let F = [3, 4];
let bothPlus = [0, ...Q, ...F, 5];
console.log(bothPlus)//[0, 1, 2, 3, 4, 5]
添加到页面上
function greeter(person: string) {
return 'Hello,' + person;
}
let user = 'Jane user';
document.body.innerHTML = greeter(user);