巧用TS

作者: 七月流火_9405 | 来源:发表于2020-05-22 17:33 被阅读0次

    1.巧用注释(/** 注释内容*/)

    场景:文件内、接口描述、方法描述、字段描述等等

    2.巧用typeof

    比如起初写法

    interface Opt {
    
      timeout: number
    
    }
    
    const defaultOption: Opt = {
    
      timeout: 500
    
    }
    

    优化后:

    const defaultOption = {
    
      timeout: 500
    
    }
    
    type Opt =typeof defaultOption
    

    3.巧用联合类型(两者必选一)

    interface Dinner1 {
    
      fish?: number,
    
      bear?: number,
    
    }
    
    type Dinner2 = {
    
      fish: number,} | {
    
      bear: number,
    }
    

    4.巧用查找类型

    interface Person {
    
      addr: {
    
        city: string,
    
        street: string,
    
        num: number,
    
      }}
    

    当需要使用 addr 的类型时,除了把类型提出来

    interface Address {
    
      city: string,
    
      street: string,
    
      num: number
    
    }
    
    interface Person {
    
      addr: Address,
    
    }
    

    5.巧用查找类型+泛型+keyof

    interface API {
    
      '/user': { name: **string** },
    
      '/menu': { foods: **Food**[] },}
    
    const get = <URL extends keyof API>(url: URL): Promise<API[URL]>=> {
    
     return fetch(url).then(res => res.json())
    
    }
    
    图片2.png

    6.巧用

    DeepReadonly  type DeepReadonly<T> = {
      readonly [P in keyof T]: DeepReadonly<T[P]>;
    }
    const a = { foo: { bar: 22 } }
    
    const b = a as DeepReadonly<typeof a>
    
    A.foo.bar=33//ok
    
    b.foo.bar=33//不ok
    

    7.as的用法

    8.interface Test{

    }

    相关文章

      网友评论

          本文标题:巧用TS

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