gpt4 book ai didi

typescript 不理解对对象数组中未定义值的过滤

转载 作者:行者123 更新时间:2023-12-02 18:12:30 25 4
gpt4 key购买 nike

我努力让 typescript 理解我已经在这个(缩短的)示例中处理一个属性(项目)的未定义情况:

interface Entry {
id: number
project?: Project
isPublished?: boolean
}

entries
.filter(entry => !!entry.project)
.map(entry => ({
title: entry.project.title
}))

(entriesEntry 的数组)并且编译器在 entry.project.title 行提示 project 属性 TS2532: Object is possibly 'undefined' 即使我有过滤器删除未定义的。另一个可选属性在过滤后仍然是可选的,因此我不能使用 Required 接口(interface):/

我怎样才能让 TS 明白这个属性是在 map 函数中明确定义的?

谢谢

-- 编辑:添加了另一个可选属性/说明作为对建议答案的回应,这将使所有属性成为必需

最佳答案

您需要将 filter 回调定义为 typeguard并使用 Required type util 使所有界面 Prop 成为必需的:

type Project = {
title: string
}

interface Entry {
id: number
project?: Project
}

type WithProject = Required<Entry>

declare const entries: Entry[]


entries
.filter((entry): entry is WithProject => !!entry.project)
.map(entry => ({
title: entry.project.title
}))

Playground

如果您对更多类型的实用程序感兴趣,请参阅 docs

关于 typescript 不理解对对象数组中未定义值的过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72086699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com