typescript之入门篇二

2019-02-13  本文已影响0人  fanstastic

属性重命名

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
}

只读属性

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

ReadonlyArray

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

额外的属性检查

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

可索引类型

interfaceArrayString {
  [index: number]: string
}

let arr: ArrayString;
arr = ['1', '2']
let str: string = arr[0]
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()
上一篇下一篇

猜你喜欢

热点阅读