跳至主要內容
TypeScript语法

基础类型

let isDone: boolean = false;
let num: number = 6
let name: string = 'zhangsan'
let notSure: any = 4 	// notSure = false  notSure='lisi'

// 数组
let arr: number[] = [1,2,3]
let arr: Array<number> = [1,2,3]

// 只读数组
let arr: ReadonlyArray<number> = [1,2,3,4]
arr[0] = 2  // error
arr.push(6) // error
arr.length  // error
let a = arr // error,赋值给新数组也不行

// 元组
let x: [string, number]
x = ['zhangsan', 28]
// x = [28, 'zhangsan'] Error

// 枚举
enum Color {Red = '#ff0000', Green = '#00ff00', Blue = '#0000ff'}
let c: Color = Color.Green

// void
function warnUser():void{
  console.log('this is a void function, no return')
}

// 对象
declare function create(o: object|null):void;
create({prop: 0})
create(null)

// 类型断言
let someValue: any = "this is a any type"
let len: number = (<string>someValue).length
let len: number = (someValue as string).length

CoderAn大约 2 分钟前端开发TypeScript