class Model { setProps (props: any) { // 这里的 any 要改成限制类的属性 Object.assign(this, props) } } class User extends Model { id!: string name!: string } const user = new User() use.setProps({ name: 'Jack', age: 100 }) // 这里 age 不是 User 的属性,能否有办法报错?
![]() | 1 Vegetable 2021-01-11 22:35:39 +08:00 class User extends Model { id!: string name!: string setProps(props: { name: string, id: string }) { super.setProps(props) } } |
![]() | 2 weijar OP 算了,自己找到答案了 seProps<T> (this: T, data: Partial<Exclude<T, 'id'>>) ts 真是太 nb 了 |
![]() | 5 weijar OP 卧槽,有新问题了,这招在 constructor 不好使?怎么办? new User({ age: 100 }) // 如果 setProps 要改成在构造器中传入 |
![]() | 6 SilencerL 2021-01-11 22:51:48 +08:00 class Model { setProps?<T>(props: T) { Object.assign(this, props) } } |
![]() | 7 weijar OP 结贴: 在构造器上目前是不可能实现的 https://github.com/microsoft/TypeScript/issues/40451 |
![]() | 8 meepo3927 2021-01-12 08:58:40 +08:00 连续自问自答, 楼主学习能力超群 |