V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Leviathann
V2EX  ›  问与答

react + typescript 想用 tagged union 来约束 react 组件的 props,实现某两个属性同时有或者同时没有,但是 switch tag 以后好像没法做到类型收窄?

  •  
  •   Leviathann · 2021-09-07 16:06:04 +08:00 · 552 次点击
    这是一个创建于 955 天前的主题,其中的信息可能已经有所发展或是发生改变。
    type BaseProps = {
        ref: React.Ref<HTMLDivElement>
        onClick: (id: number) => React.MouseEventHandler<HTMLDivElement>
    }
    
    type MyProps = 
      | BaseProps & {type: 'a', length: number ...}
      | BaseProps & {type: 'b', width: number ...}
    
    class MyComponent extends PureComponent<MyProps> {
      
      render() {
        const {type} = this.props;
        
        switch (type) {
          case 'a': {
            const {length} = this.props 
          }
      }
    }
    

    取 length 的地方就报错,说找不到这个属性

    TS2339: Property 'length' does not exist on type 'Readonly{ children?: ReactNode; }> & Readonly '.
    

    是不支持这样写还是我的写法有问题

    4 条回复    2021-09-07 16:26:46 +08:00
    Leviathann
        1
    Leviathann  
    OP
       2021-09-07 16:22:13 +08:00
    发现使用的地方的确实现了某几个属性同时有或者同时没有的检查,但是组件里怎么类型安全的把它们取出来。。
    noe132
        2
    noe132  
       2021-09-07 16:24:51 +08:00   ❤️ 1
    你需要 switch (this.props.type)
    目前 typescript 并不支持你从对象中的键赋值给 const 变量来做 control flow analysis
    这个功能应该将会在 typescript 4.4 支持。升级 4.4 后你的代码就不会报错了。或者直接使用 typescript@beta
    noe132
        4
    noe132  
       2021-09-07 16:26:46 +08:00
    原来 4.4 早就已经发布了~那你只需要升级一下 typescript 版本就行了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1514 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 17:05 · PVG 01:05 · LAX 10:05 · JFK 13:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.