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

2021-09-07 16:06:04 +08:00
 Leviathann
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 '.

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

559 次点击
所在节点    问与答
4 条回复
Leviathann
2021-09-07 16:22:13 +08:00
发现使用的地方的确实现了某几个属性同时有或者同时没有的检查,但是组件里怎么类型安全的把它们取出来。。
noe132
2021-09-07 16:24:51 +08:00
你需要 switch (this.props.type)
目前 typescript 并不支持你从对象中的键赋值给 const 变量来做 control flow analysis
这个功能应该将会在 typescript 4.4 支持。升级 4.4 后你的代码就不会报错了。或者直接使用 typescript@beta
noe132
2021-09-07 16:25:32 +08:00
noe132
2021-09-07 16:26:46 +08:00
原来 4.4 早就已经发布了~那你只需要升级一下 typescript 版本就行了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/800430

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX