打字稿错误地假设元素“可能”未定义

问题描述 投票:0回答:1

假设如下:

interface HandleMapDefaultProps {
    item: {
        id: number
    } & Record<string, unknown>;
    renderCustomComponent?: never;
}

interface HandleMapCustomProps {
    renderCustomComponent: () => HTMLElement;
    item?: never;
}

type HandleMapProps = MapDefaultProps | MapCustomProps;
const handleMap = ({
    item,
    renderCustomComponent
} : MapProps): HTMLElement => renderCustomComponent?.() ?? <div>{item.id}</div>

这会引发错误,

'item' is possibly 'undefined'

但是根据为 props (

MapProps
) 提供的类型,如果
renderCustomComponent
未定义,则
item
将始终被定义。

item!.id
解决了这个问题,但我想知道是否有更好的方法?

javascript typescript
1个回答
0
投票

TypeScript 似乎无法通过这样的可选链函数调用进行推断。您可以使用对我有用的三元运算符:

interface HandleMapDefaultProps {
  item: {
    id: number;
  } & Record<string, unknown>;
  renderCustomComponent?: never;
}

interface HandleMapCustomProps {
  renderCustomComponent: () => HTMLElement;
  item?: never;
}

type HandleMapProps = HandleMapDefaultProps | HandleMapCustomProps;

const handleMap = ({
  item,
  renderCustomComponent,
}: HandleMapProps): HTMLElement | number =>
  renderCustomComponent ? renderCustomComponent() : item.id;

(我修改了此示例的返回类型,因为在我的环境中 JSX 元素不返回 HTMLElement。上面的代码能够推断出必须定义

item
。)

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.