TypeScript类型

数组

const arr1: Array<number> = [1, 2, 3]
const arr2 : number[] = [1, 2, 3]
和 Flow 一样


例子
function sum(...args: number[]) {
要求 reset 方式传入的参数必须都为 Int
}

元组

const tuple: [number, string] = [1, 'zce']

const age = tuple[0]
const name = tuple[1]

枚举

enum PostStatus {
Draft = 0
Unpublish
}


enum PostStatus {
Draft = 'aaa'
Unpublish = 'bbb'
}

常量枚举
const enum Post {

}

函数类型

function func1 (a: number, b?<可选参数>: number): string {
return 'func1'
}

function func1 (a: number, b: number = 1 ): string {
return 'func1'
}

函数表达式(匿名函数)
const func2 = function (a: number, b: number): string {
return 'func1'
}


###任意类型any

function stringily(value: any) {
return JSON.string(value)
}


###隐式类型推断
同Swift初始化时赋予什么类型就是什么类型
不同的是可以第一次赋值时推断

###类型断言 as 、<Type>

const num = [110, 120]
const res = num.find(I => I > 0)
const num1 = res as number
const num2 = <number>res


#interface 对应Swift协议

interface Post {
title: string
content: string
subtitle?: string // 可选
readonly summary: string // 只读
}

function printPost(post: Post) {
}

interface Cache {
[prop: string] : string // 可以表示 任意 key为string类型值为string类型的对象
}


###类

class Person {
name:string
age: number = 1
constructor(name: string, age: number) {
this.name = name
this.age = age
}
}


###类中访问修饰

class Person {
private name: string // 只能在
public age: number
protected gender: boolean// 只允许在子类中访问
}


只读属性

class Person {
readonly name: string = 'sd'
}


interface EatAndRun {
eat(foo: string): void
run(distance: number): void
}

interface Jump {
jump(her: number): void
}
class Person implements EatAndRun, Jump {
/// 协议中方法都是 @require
}

### 抽象类

abstract class Animal {
eat(food: string): void {
}
abstract run(food: string): void
}
abstract 只能被继承不能被实例
抽象方法可以不实现 但子类必须实现
class Dog extends Animal {
}


###泛型
function createNumberArray<T> (long: T)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容