Typescript强制实现可选接口成员

dis*_*nte 4 typescript

给定接口

interface IAmOptional {
   optional? : string,
   optional2?: string
   forced: string
}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以掩盖,扩展或类似IAmOptional方式导致此实施失败?

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

jca*_*alz 6

是的,从TypeScript 2.8开始,有一种方法可以使用映射类型的语法以编程方式从属性中删除可选修饰符-?

type Required<T> = { [K in keyof T]-?: T[K] }
Run Code Online (Sandbox Code Playgroud)

这为您提供了您想要的行为:

class someClass {
  thisShouldHaveAllKeys: Required<IAmOptional> = {  // error!
//~~~~~~~~~~~~~~~~~~~~~ <-- missing properties optional1, optional2
    forced: 'i am forced'
  }
}
Run Code Online (Sandbox Code Playgroud)

实际上,这种Required类型的别名非常有用,可以在标准库中为您预定义。因此,您无需定义即可使用它。

希望能有所帮助。祝好运!