V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
weijar
V2EX  ›  TypeScript

Typescript 能否达成这个效果?

  •  
  •   weijar · 2021 年 1 月 11 日 · 2653 次点击
    这是一个创建于 1827 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2021-01-12 08:58:40 +08:00
    Vegetable
        1
    Vegetable  
       2021 年 1 月 11 日
    class User extends Model {
    id!: string
    name!: string
    setProps(props: { name: string, id: string }) {
    super.setProps(props)
    }

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

    ts 真是太 nb 了
    weijar
        3
    weijar  
    OP
       2021 年 1 月 11 日
    @Vegetable 你这个不通用啊
    Vegetable
        4
    Vegetable  
       2021 年 1 月 11 日
    @weijar 是挺牛逼...
    weijar
        5
    weijar  
    OP
       2021 年 1 月 11 日
    卧槽,有新问题了,这招在 constructor 不好使?怎么办?
    new User({ age: 100 }) // 如果 setProps 要改成在构造器中传入
    SilencerL
        6
    SilencerL  
       2021 年 1 月 11 日
    class Model {
    setProps?<T>(props: T) {
    Object.assign(this, props)
    }
    }
    weijar
        7
    weijar  
    OP
       2021 年 1 月 11 日
    结贴: 在构造器上目前是不可能实现的
    https://github.com/microsoft/TypeScript/issues/40451
    meepo3927
        8
    meepo3927  
       2021 年 1 月 12 日
    连续自问自答, 楼主学习能力超群
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   3625 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 04:31 · PVG 12:31 · LAX 20:31 · JFK 23:31
    ♥ Do have faith in what you're doing.