正确声明接口或键入功能参数
如何正确声明param cardbystatus 内部功能 addcardstostatus 的类型?它适用于 cardbystatus:任何,但对我来说没有意义。
错误:属性'map'在类型'{cards:number []; }'
enum HealthPlanStatus {
InProgress = 'InProgress',
Completed = 'Completed',
}
type ICardsByStatus = {
[status in HealthPlanStatus]:{
cards: number[]
}
}
interface IOptions {
optionsStatus: string
}
function addCardsToStatus(cardsByStatus: ICardsByStatus, options: IOptions) {
const {optionsStatus}: IOptions = options
cardsByStatus[optionsStatus].map((card:number) => card)
cardsByStatus["InProgress"].map((card:number) => card)
}
const cardsByStatus = { InProgress: { cards: [] }, Completed: { cards: [ 1, 2, 3 ] } }
const options = { optionsStatus: 'InProgress' }
addCardsToStatus(cardsByStatus, options)
How to correctly declare type for param cardsByStatus inside function addCardsToStatus? It works for cardsByStatus: any, but it doesn't make sense for me.
Error: Property 'map' does not exist on type '{ cards: number[]; }'
enum HealthPlanStatus {
InProgress = 'InProgress',
Completed = 'Completed',
}
type ICardsByStatus = {
[status in HealthPlanStatus]:{
cards: number[]
}
}
interface IOptions {
optionsStatus: string
}
function addCardsToStatus(cardsByStatus: ICardsByStatus, options: IOptions) {
const {optionsStatus}: IOptions = options
cardsByStatus[optionsStatus].map((card:number) => card)
cardsByStatus["InProgress"].map((card:number) => card)
}
const cardsByStatus = { InProgress: { cards: [] }, Completed: { cards: [ 1, 2, 3 ] } }
const options = { optionsStatus: 'InProgress' }
addCardsToStatus(cardsByStatus, options)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该首先更改接口
ioptions
:如果
optionsstatus
定义为String
,则不允许使用它来对类型的对象进行索引。代码> iCardsbystatus 。您还定义了
iCardBystatus
具有附加密钥{cards:number []}
。要访问数组,您应该使用此密钥。最后,如果将
选项
传递给该方法,如果将其定义为带有string
内部的对象,现在将投诉。 So we should change it to this:You should first change the interface
IOptions
:If
optionsStatus
is defined asstring
, it is not allowed to use it to index on object of typeICardsByStatus
.You also defined
ICardByStatus
to have an additional key{ cards: number[] }
. To access the array, you should use this key.And lastly TypeScript will now complain if you pass
options
to the method if you defined it as an object with astring
inside. So we should change it to this:Playground