美文网首页
typescript之入门篇二

typescript之入门篇二

作者: fanstastic | 来源:发表于2019-02-13 15:29 被阅读0次

属性重命名

const { a: newName1, b: newName2 } = { a: 1., b: 2 }

默认值

interface params {
  a: number;
  b?: number; 
}
function test(obj: params): void {
  const { a, b = 1200 } = params
  consoloe.log(b) // 1200
}
  • 当缺省的b为undefined时,给一个默认的1200
  • ?的作用代表可传可不传
  • void 代表没有返回值

只读属性

interface params {
    readonly a?: number;
    readonly b?: number;
}

const xxx: params = {
  a: 1,
  b: 2
}
const { a } = xxx
a = 100
consolo.log(a) // 100
xxx.a = 100 // error
  • 通过解构的方式可以修改值, 但是不能直接修改对象中的值
  • readonly表示此属性只读

ReadonlyArray

  • typescript 具有ReadnolyArray类型
let a: number[] = [1, 2, 3, 4]
let ro: ReadonlyArray<number> = a
ro.push(1000) // error
a.push(2000) // ro 和 a均为[1, 2, 3, 4, 1000]

readonly vs const

  • readonly作用于属性, const 作用于变量

额外的属性检查

  • 当我们需要传入一个未知属性时,同时对这个未知属性检查
interface configProp {
  color?: string;
  width?: number;
  [propName: string]: any
}

function createConfig(config: configProp): { color: string }{
  xxx
  return { color: 'green' }
}

createConfig({ randomValue: string })

函数类型

  • 接口不仅能定义函数参数,也能定义函数
interface searchProps {
  (a: string, b?: string): boolean
}

let search: searchProps;
search = function(){
  return true
}
search()  //error
search('123') // true

可索引类型

  • 使用number类型的索引会返回string类型的字符串
interfaceArrayString {
  [index: number]: string
}

let arr: ArrayString;
arr = ['1', '2']
let str: string = arr[0]
  • 编译时会出现error,因为number类型的索引只能返回number类型的字符串,而name返回的是string类型的字符串,所以要修改成name: number
interface NumberDic {
  readonly [index: number]: number;
  name: string
}

实现接口

interface Clock {
  currentTime: Date;
  setTime(d: Date): void;
}

class Clo implements Clock {
  currentTime: Date
  setTime(d: Date){}
  constructor(h: number, m: number){}
}

继承接口

interface Shape {
  color: string;
}

interface Size {
    width: number;
}

interface S extends Shape, Size {
  xxx: string;
}

let a = <S>{}
a.xxx = '123'

混合类型

interface Counter {
  (start: number): string;
  interval: number;
  reser(): void;
}

function getCounter(): Counter {
  let counter = <Counter>function(start: number){}
  return counter;
}

let c = getCounter()

相关文章

网友评论

      本文标题:typescript之入门篇二

      本文链接:https://www.haomeiwen.com/subject/undkeqtx.html