TypeScript联合类型中按类型key访问属性仍报错的问题求助
TypeScript联合类型中按类型key访问属性仍报错的问题求助
我现在遇到一个特别费解的TypeScript问题,想请教大家!
我明明已经通过FeedTypes的key来访问对应的属性了,但TypeScript还是报错说属性不存在,这完全说不通啊!
先给大家看看我的代码情况:我定义了一个联合类型ChatHeaderProps,分成两种场景——当type是FeedTypes.CONVERSATION时,包含lastSeenAt属性;当type是FeedTypes.GROUP时,包含members属性。然后我在组件里写了一个titles对象,想用props.type作为key来对应不同的文本内容,结果访问props.lastSeenAt和props.members的时候都报错了。
具体代码如下:
export type ChatHeaderProps = | { name: string; isVerified?: boolean; type: FeedTypes.CONVERSATION; lastSeenAt: string; } | { name: string; isVerified?: boolean; type: FeedTypes.GROUP; members: number; }; const ChatHeader = (props: ChatHeaderProps) => { // 其他业务代码... const titles: Record<Exclude<FeedTypes, 'user'>, string> = { conversation: `last seen ${getRelativeTimeString(new Date(props.lastSeenAt), 'en-US')}`, group: `${props.members} members`, } return ( // 其他JSX结构 <Typography as='p' variant='secondary'> {titles[props.type]} </Typography> ) }
我知道可以用严格相等判断来绕开这个问题,比如写if (props.type === FeedTypes.CONVERSATION)之后再去访问lastSeenAt,但这真的没必要啊!因为我已经通过props.type作为key来区分两种情况了,为什么TypeScript还是没法正确推断类型呢?有没有什么办法能让TypeScript识别这里的逻辑,不用额外加冗余的判断?
备注:内容来源于stack exchange,提问作者Flain
相关产品推荐
相关产品推荐

