weijar

Typescript 能否达成这个效果?

  •  
  •   weijar · Jan 11, 2021 · 3304 views
    This topic created in 2138 days ago, the information mentioned may be changed or developed.
    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 的属性,能否有办法报错?
    
    8 replies  •  2021-01-12 08:58:40 +08:00
    Vegetable
    Vegetable
    Jan 11, 2021
    1
    class User extends Model {
    id!: string
    name!: string
    setProps(props: { name: string, id: string }) {
    super.setProps(props)
    }

    }
    weijar
    weijar
    OP
    Jan 11, 2021
    2
    算了,自己找到答案了
    seProps<T> (this: T, data: Partial<Exclude<T, 'id'>>)

    ts 真是太 nb 了
    weijar
    weijar
    OP
    Jan 11, 2021
    3
    @Vegetable 你这个不通用啊
    Vegetable
    Vegetable
    Jan 11, 2021
    4
    @weijar 是挺牛逼...
    weijar
    weijar
    OP
    Jan 11, 2021
    5
    卧槽,有新问题了,这招在 constructor 不好使?怎么办?
    new User({ age: 100 }) // 如果 setProps 要改成在构造器中传入
    SilencerL
    SilencerL
    Jan 11, 2021
    6
    class Model {
    setProps?<T>(props: T) {
    Object.assign(this, props)
    }
    }
    weijar
    weijar
    OP
    Jan 11, 2021
    7
    结贴: 在构造器上目前是不可能实现的
    https://github.com/microsoft/TypeScript/issues/40451
    meepo3927
    meepo3927
    Jan 12, 2021
    8
    连续自问自答, 楼主学习能力超群
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2136 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 14:04 · PVG 22:04 · LAX 06:04 · JFK 09:04
    ♥ Do have faith in what you're doing.