
class Model { setProps (props: any) { // 这里的 any 要改成限制类的属性 Object.assign(this, props) } } class User extends Model { id!: string name!: string } const user = new User() user.setProps({ name: 'Jack', age: 100 }) // 这里 age 不是 User 的属性,能否有办法报错? 1 Vegetable Jan 11, 2021 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 Jan 11, 2021 class Model { setProps?<T>(props: T) { Object.assign(this, props) } } |
7 weijar OP 结贴: 在构造器上目前是不可能实现的 https://github.com/microsoft/TypeScript/issues/40451 |
8 meepo3927 Jan 12, 2021 连续自问自答, 楼主学习能力超群 |