Typescript 类方法,受限于类属性

标签 typescript

给定以下类(class):

class MyOb {
  foo: string; 

  setFields(props) {
    Object.assign(this, props);
  }
}

是否可以将 setFieldsprops 参数限制为 MyObj 的属性?这样:

new MyOb().setFields({ foo: 'bar' })  // compiles
new MyOb().setFields({ x: 'bar' })    // fails, property x is not a part of MyOb

最佳答案

您正在寻找 keyof 和映射类型:

setFields(props: { [TKey in keyof MyOb]?: MyOb[TKey] } ) {

请注意 ?,因为您希望每个属性都是可选的。

Demo

Docs

关于Typescript 类方法,受限于类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49807176/

相关文章:

typescript - 如何在带有 TypeScript 的 Next.js 中将 next-auth 与每页布局一起使用?

javascript - TypeScript - 如何覆盖 lib.d.ts 中的声明?

javascript - Angular 12 中组件属性的初始化?

TypeScript:将 `Pick<T, K>` 分配给 `Partial<T>`

typescript - NestJS - WebsocketGateway 中的 ValidationPipe 返回内部服务器错误

angular - 使用 [ngClass] 条件只能正确显示一种 Font Awesome 图标

javascript - Express Typescript 不使用中间件

angular - 如果每个 observable 都有新数据,我如何才能一次订阅 angular2 中的多个 observable 并等待?

angular - typescript 错误 : Property 'files' does not exist on type 'HTMLElement'

typescript - 错误 TS2532 : Object is possibly 'undefined' after checking if it is defined