在线练习: http://www.typescriptlang.org/play/index.html
一、字符串
1.使用``可以实现多行字符串
2.字符串模板
function getName(){
return "hello"
}
var name:string = 'xxx'
console.log(`
<div>
<span>${name}</span>
<span>${getName()}</span>
</div>
`)
3.自动拆分字符串
function test(template, name, age) {
console.log(template)
console.log(name)
console.log(age)
}
var myname = "pipi"
var getAge = function () {
return 18;
}
test `hello my name is ${myname}, i'm ${getAge()}`
打印结果为:Array... pipi 18 , 数组由两个参数分割为三部分。
二、变量类型
可以通过这样 var name:string = "xxx" 来个参数指定类型
如果没有显示的设置类型,那么就会根据第一次赋值时的类型来推断这个变量的类型
类型的种类:string 、number 、boolean 、void, void用于方法返回值
function test(name: string): string{
return "hello"
}
三、自定义类型
class Person{
name: string;
age: number;
}
var p: Person = new Person();
p.name = "pipi";
p.age = 18
四、参数
1.可选参数和参数默认值:
function test(a: string, b?: string, c: string = "pipi") {
console.log(a,b,c)
}
test("xxx", "bbb", "sss");
test("ccc", "ddd")
test("aaa")
注意点:带默认值的参数和可选参数必须放到最后
打印结果:
xxx bbb sss
ccc ddd pipi
aaa undefined pipi
2.任意参数
function func1(...args) {
args.forEach(function (arg) {
console.log(arg)
})
}
func1(1, 2, 3)
func1(1,2,3,3,4,5,6)
function func1(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
var args = [1, 2]
func1(...args);
var args2 = [1, 2, 3, 3, 4, 5, 5]
func1(...args2)
五、析构表达式
function getInfo() {
return {
name: "pipi",
age: 18
}
}
var info = getInfo()
var name0 = info.name
var age0 = info.age
console.log(`${name0}...${age0}`)
var { name, age } = getInfo();
console.log(`${name}...${age}`)
var { name: namex, age: agex } = getInfo();
console.log(`${namex}...${agex}`)
function getInfo() {
return {
state: true,
msg: {
name: "pipi",
age:18
}
}
}
var { state: s, msg: { name: n, age: a } } = getInfo()
console.log(s,n,a)
var arr = [1, 2, 3, 4, 5]
var [n1, n2, ...others] = arr
console.log(n1, n2, others)
1 2 Array(3)
var arr = [1, 2, 3, 4, 5]
function test([n1, n2,...others]) {
console.log(n1,n2,others)
}
test(arr)
六、箭头表达式
var f1 = () => {
return "t1"
}
console.log(f1())
var arg0 = "t"
var f2 = arg0 => {
return arg0+"2"
}
console.log(f2(arg0))
var arg1 = 1;
var arg2 = 2;
var sum = (arg1, arg2) => arg1 + arg2;
console.log(sum(arg1,arg2))
var arg3 = 3
var arg4 = 4
var opt = (argx, argy) => {
return argx * argx + argy * argy;
}
console.log(opt(arg3,arg4))
var marr = [1, 2, 3, 4, 5]
console.log(marr.filter(value => value % 2 == 0))
//2 4
使用箭头表达式的优点:this 在函数内外是统一的
七、for of 循环
var arr = [1, 2, 3, 4, 5]
arr.last = "six"
//忽略属性值,不能break 1,2,3,4,5
arr.forEach(value => console.log(value))
//循环的是key 0,1,2,3,4,last
for (var n in arr) {
console.log(n)
}
//循环的value,忽略属性值 1,2,3,4,5
for (var t of arr) {
console.log(t)
}
八、面向对象特性
...