TypeScript 語法
變量賦值
常用類型賦值
let foo = 'bar';
foo = 'baz';
foo = []
const count = 0;
let isDone: boolean = true;
let num: number = 10;
字符串引用數(shù)據(jù)
let user = {
name: 'jack',
age:18
}
let str: string = `
hello,我叫${user.name}
今年${user.age}
`;
數(shù)組元祖賦值
let arr: Array<number> = [1, 2, 3]
let arr: string[] = ['hello', 'hehe']
//元祖結(jié)構(gòu)
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)
函數(shù)類型聲明
類型除了用于變量聲明之后,還可以用于函數(shù)的形象
function add(x:number, y:number):number {
return x+y
}
var ret = add(10, 20)
函數(shù)空返回值
function fn(): void{
console.log('hello')
}
數(shù)組的解構(gòu)
let arr: number[] = [10, 20]
let num1: number = arr[0]
// 按照順序解構(gòu)賦值
let [num1,num2] = arr
對象的解構(gòu)
let user = {
name: 'Jack',
age: 18
}
//對象按照屬性名稱解構(gòu)
//在瀏覽器環(huán)境中,window對象本身有個(gè)name
// name的重命名
let { name: nickname, age } = user
function add([x,y]) {
return x + y
}
add([1,2])
剩余參數(shù) (不定參數(shù))
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'
}