标签搜索

typescript学习笔记二

cicaba
2019-04-22 / 0 评论 / 2 阅读 / 正在检测是否收录...

函数
返回值的类型定义

fu(): void{}

函数的参数必须定义类型

fu(name: string, age: number){}

函数的默认值

fu(name: string = "小米", age: number = 9) {}

接口
接口的作用: 在面向对象的编程中, 接口是一种规范的定义, 它定义了行为和动作的规范, 在程序设计里面,接口起定义标准的作用.

  1. 接口的可选属性, 在属性的名的后面添加一个问号(?).
  2. 只读属性, 在属性名前添加一个readonly.
  3. 只读数组类型, readonly Array<数组元素类型>. 注意把一个普通数组赋值给readonlyArray后普通数组也只可读.
interface Job {
  type: string;
  jobTime?: string;
  description(): string;
}
class Mi implements Job {
  readonly type: string;
  jobTime: string;
  constructor(type: string, jobTime: string = "8") {
    this.type = type;
    this.jobTime = jobTime;
  }
  description() {
    return this.type + '工作' + this.jobTime + "小时;"
  }
}

console.log(new Mi("小米").description());
  1. 函数类型接口, 用来定义函数的参数列表,和返回值的类型的定义.参数列表使用小括号():返回值的类型. 如:(height:string,width:string):boolean;
interface Job {
  (jobTime: string, type?: string): string;
}
class Mi {
  readonly type: string;
  jobTime: string;
  constructor(type: string, jobTime: string = "8") {
    this.type = type;
    this.jobTime = jobTime;
  }
  description: Job = (jobTime: string, type: string) => {
    this.jobTime = jobTime;
    return this.type + '工作' + this.jobTime + "小时;";
  }
}

console.log(new Mi("小米").description("9"));
  1. 可索引的类型, 它具有一个索引签名, 签名的类型只有两种(number,string). 还有相应的索引返回值类型.如:readonly [index:number]:string. (只读索引)
interface Job {
  [index: string]: string;
}
class Mi {
  readonly type: string;
  jobTime: string;
  constructor(type: string, jobTime: string = "8") {
    this.type = type;
    this.jobTime = jobTime;
  }
  description(jobTime: string, type?: string): object {
    this.jobTime = jobTime;
    let obj: Job = {
      type: this.type,
      jobTime: this.jobTime
    }
    return obj
  }
}

console.log(new Mi("小米").description("9"));
0

评论 (0)

取消