可选接口(interface)成员的 typescript 强制实现

标签 typescript

<分区>

给定一个接口(interface)

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 2.8 开始,有一种方法可以 programmatically remove the optional modifier from propertiesmapped types 中使用 -? 语法:

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。 .所以你可以直接使用它而无需定义它。

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

关于可选接口(interface)成员的 typescript 强制实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54368695/

相关文章:

linux - 从 Angular 4 组件运行 Linux 命令

javascript - 传单将坐标转换为街道地址

typescript - 为什么 Visual Studio 2017 不在 TypeScript 文件上使用 ESLint?

typescript 选择问题

javascript - 无法转换包含异步等待的 TypeScript

angular - ngIf- 表达式在检查后发生了变化。先前值 : 'ngIf: false' . 当前值: 'ngIf: true'

javascript - 为什么 typescript 看不到我的功能?

javascript - Chart.js 中未显示折线图

javascript - Typescript,准确表示类方法行为

javascript - VSCode 调试器不会在 Typescript 断点处停止