gpt4 book ai didi

javascript - 基于key的流对象值

转载 作者:行者123 更新时间:2023-12-03 00:12:07 27 4
gpt4 key购买 nike

当使用流程时,我一直想输入这样的内容:

type Item = {
timestamp: number,
status: { completed: boolean },
data: string,
}

type Filter = {
timestamp: number,
status: { completed: boolean },
}

const FilterFns: {
[key: $Keys<Filter>]: ($ElementType<Filter, key>, item: Item) => boolean
} = {
timestamp: (timestamp, item) => timestamp === item.timestamp,
status: (status, item) => status.completed === item.status.completed,
}

但我收到错误:

13:   [key: $Keys<Filter>]: ($ElementType<Filter, key>, item: Item) => boolean
^ Cannot resolve name `key`.

如果我将 FilterFns 定义为:

const FilterFns: {
[key: $Keys<Filter>]: ($Values<Filter>, item: Item) => boolean
} = {
timestamp: (timestamp, item) => timestamp === item.timestamp,
status: (status, item) => status.completed === item.status.completed,
}

我收到错误:

16:   status: (status, item) => status.completed === item.status.completed,
^ Cannot get `status.completed` because property `completed` is missing in `Number` [1].
References:
8: timestamp: number,
^ [1]

确保传入函数的 FilterFns 值中的第一个参数是 Filter 中对应类型的正确方法是什么?

最佳答案

不是对象键问题的通用解决方案,但可以通过下一种方式解决特定情况

type Item = {
timestamp: number,
status: { completed: boolean },
data: string,
}

type Filter = {
timestamp: number,
status: { completed: boolean },
}

const FilterFns: {
[key: $Keys<Filter>]: ($Values<Filter>, item: Item) => boolean
} = {
timestamp: (timestamp, item) => timestamp === item.timestamp,
status: (status, item) => typeof status === 'object' && status.completed === item.status.completed,
}

添加附加条件typeof status === 'object'将允许流程识别现在的确切值,否则不幸的是,流程无法获得正确的键对-值

关于javascript - 基于key的流对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54680375/

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