V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Leviathann
V2EX  ›  问与答

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

  •  
  •   Leviathann · Sep 7, 2021 · 934 views
    This topic created in 1699 days ago, the information mentioned may be changed or developed.
    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 replies    2021-09-07 16:26:46 +08:00
    Leviathann
        1
    Leviathann  
    OP
       Sep 7, 2021
    发现使用的地方的确实现了某几个属性同时有或者同时没有的检查,但是组件里怎么类型安全的把它们取出来。。
    noe132
        2
    noe132  
       Sep 7, 2021   ❤️ 1
    你需要 switch (this.props.type)
    目前 typescript 并不支持你从对象中的键赋值给 const 变量来做 control flow analysis
    这个功能应该将会在 typescript 4.4 支持。升级 4.4 后你的代码就不会报错了。或者直接使用 typescript@beta
    noe132
        4
    noe132  
       Sep 7, 2021
    原来 4.4 早就已经发布了~那你只需要升级一下 typescript 版本就行了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1281 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 16:52 · PVG 00:52 · LAX 09:52 · JFK 12:52
    ♥ Do have faith in what you're doing.