TypeScript 语法
变量赋值
常用类型赋值
let foo = 'bar';
foo = 'baz';
foo = []
const count = 0;
let isDone: boolean = true;
let num: number = 10;
字符串引用数据
let user = {
name: 'jack',
age:18
}
let str: string = `
hello,我叫${user.name}
今年${user.age}
`;
数组元祖赋值
let arr: Array<number> = [1, 2, 3]
let arr: string[] = ['hello', 'hehe']
//元祖结构
let arr:[number,string] = [11,'hehe']
let user:object = {
name: 'Jack',
age:18
}
接口与对象赋值
接口定义
interface Person {
name: string,
age: number
}
let user: {
name: string,
age: number
} = {
name: 'Jack',
age: 11
}
let zs: Person = {
name: 'zs',
age: 12
}
any的使用
// 在不确定类型的情况下可以使用 anyany
let num: any = 10
num = '20'
let ret: string = (num as string).substr(1)
函数类型声明
类型除了用于变量声明之后,还可以用于函数的形象
function add(x:number, y:number):number {
return x+y
}
var ret = add(10, 20)
函数空返回值
function fn(): void{
console.log('hello')
}
数组的解构
let arr: number[] = [10, 20]
let num1: number = arr[0]
// 按照顺序解构赋值
let [num1,num2] = arr
对象的解构
let user = {
name: 'Jack',
age: 18
}
//对象按照属性名称解构
//在浏览器环境中,window对象本身有个name
// name的重命名
let { name: nickname, age } = user
function add([x,y]) {
return x + y
}
add([1,2])
剩余参数 (不定参数)
function sum(...args: number[]):number{
let ret = 0
args.forEach(function (item){
ret += item
})
return ret
}
sum(1, 2, 3)
展开操作符
let arr1 = [1, 2, 3]
let arr2 = [4, 5, 6, ...arr1]
let arr = [...arr1, ...arr2]
let obj1 = {
foo:'bar'
}
let obj2 = {
...obj1,
name:'Jack'
}
网友评论