【问题标题】:Typescript force implementation of optional interface members [duplicate]可选接口成员的打字稿强制实现[重复]
【发布时间】:2019-06-19 11:45:52
【问题描述】:

给定一个接口

interface IAmOptional {
   optional? : string,
   optional2?: string
   forced: string
}

有没有办法以这种实现失败的方式隐藏、扩展或类似IAmOptional

class someClass {
    thisShouldHaveAllKeys : IAmOptional  = { // Forced<IAmOptional> ??
        forced: 'i am forced'
    }  // Here I want an error like 'thisShouldHaveAllKeys does not have optional and optional2' 
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以使用第二个接口来覆盖可选成员:

    interface IAmOptional {
      optional? : string,
      optional2?: string
      forced: string
    }
    
    interface IAmNotOptional extends IAmOptional {
      optional: string;
      optional2: string;
    }
    

    它不是很优雅,但可以解决问题。另一种方法是将问题颠倒过来并利用 Typescript 的Partial 功能:

    interface IAmNotOptional {
      optional: string;
      optional2: string;
      forced: string;
    }
    
    class A {
      all: IAmNotOptional = { forced: 'forced' }; // error
      some: Partial<IAmNotOptional> = { forced: 'forced' }; // no error
      none: Partial<IAmNotOptional> = { }; // no error, but perhaps undesirable behaviour
    }
    

    【讨论】:

      【解决方案2】:

      是的,从 TypeScript 2.8 开始,有一种方法可以使用 -? 语法和 mapped types programmatically remove the optional modifier from properties

      type Required<T> = { [K in keyof T]-?: T[K] }
      

      这会给你想要的行为:

      class someClass {
        thisShouldHaveAllKeys: Required<IAmOptional> = {  // error!
      //~~~~~~~~~~~~~~~~~~~~~ <-- missing properties optional1, optional2
          forced: 'i am forced'
        }
      }
      

      事实上,这个Required 类型别名非常有用,它是predefined for you in the standard library。所以你可以直接使用它而不定义它。

      希望对您有所帮助。祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-04
        • 2021-12-03
        • 2017-06-29
        • 2017-08-31
        • 2019-03-26
        • 2016-11-30
        • 1970-01-01
        相关资源
        最近更新 更多