1.变量声明
let msg:string='hello world'
const PI:number=3.141592653
let stringData:string='hello typescript' //string
let age:number=18 //number
let finished:boolean=true //boolean
let a:any='any' //any 不确定类型
let u:string|number|boolean='union'//union联合类型 可以多个指定类型中的一种
let o={name:'java',age:21} //object对象
console.log(p.name)
console.log(p['name'])
let names:Array<string>=['jack','rose']//array数组
let ages:number[]=[21,28]
console.log(name[0])
2.条件控制
//空字符串、数字0、null、undefined 的被认定为false 其他值则为true
if(num){//判空
//num 不为null 0 有值
}
//if-else
let num:number=21
if(num%2===0){ //==会去判断两端的类型,不一致会去做转换,性能损耗
console.log(num+'是偶数')
}else{
console.log(num+'是奇数')
}
//switch
let chengji:string='A'
switch(chengji){
case 'A':{
console.log('优秀')
break
}
case 'B':{
console.log('合格')
break
}
case 'C':{
console.log('不合格')
break
}
default:{
console.log('非法输入')
break
}
}
3.循环迭代
//for
for(let i=0;i<=10;i++){
console.log('点赞'+i+'次')
}
//数组 for in 数组角标
let names:string[]=['jack','rose']
for(const i in names){
console.log(i+':'+names[i])
}
//for of 元素数据
for(const name of names){
console.log(name)
}
//foreach
names.forEach((value,index)=>{
console.log(value); //'jack' 'rose'
});
//while
let i=1;
while(i<=10){
console.log('点赞'+i+'次')
i++;
}
4.函数
//无返回值函数
function sayHello(name:string):void{
console.log('你好'+name+'!')
}
sayHello('小明')
//有返回值函数
function sum(x:number,y:number):number{
return x+y
}
let result=sum(21,18)
//箭头函数
let sayHi=(name:string)=>{
}
let hasBackData=(x:number,y:number):number=>{
return x+y
}
let result=hasBackData(21,18)
//可选参数
function sayHello(name?:string){
name=name?name:'陌生人'
console.log('你好'+name+'!')
}
sayHello('tom') //你好tom!
sayHello() //你好陌生人!
//默认参数
function sayHello(name:string='陌生人'){
console.log('你好'+name+'!')
}
sayHello('tom') //你好tom!
sayHello() //你好陌生人!
5.类和接口
interface、class、enum
//枚举
enum Msg{
HI='HI',
HELLO='HELLO'
}
//接口
interface A{
say(msg:Msg):void
}
//类
class B implements A{
say(msg:Msg):void{
console.log(msg+',I am B')
}
}
//初始化实例
let a:A=new B()
//调用方法
a.say(Msg.HI)
6.模块开发
export class Rectangle{
public width:number
public length:number
constructor(width:number,length:number){
this.width=width
this.length=length
}
}
export function area(rec:Rectangle):number{
return rec.width*rec.length
}
//使用
import {Rectangle,area} from '../rectangle'