【问题标题】:Declare array index in typescript在打字稿中声明数组索引
【发布时间】:2019-02-12 09:44:27
【问题描述】:

我有这个 AjaxResponse 接口:

interface AjaxResponse {
    calendar: {
        dates: {
            date: string,
            hours: {
                hour: string,
                id: number,
                status: string,
                client: {
                    name: string,
                    surname: string,
                    email: string,
                    phone: string,
                    id: number
                }
            }[]
        }[]
    },
    rights: string,
    listenerUrl: string
}

我将遍历日期列表并编辑其中一些:

let dates: AjaxResponse['calendar']['dates']
let i: number
let l: number

    receive(response: AjaxResponse) {
                dates = response.calendar.dates
                l = dates.length
                for (i; i < l; i++) {
                    calendar.editDates(dates[i])
                }

日期编辑功能如下:

editDates(newDate: AjaxResponse['calendar']['dates']) {
    }

dates[i] 无法编译,因为我的最后一个函数需要一个数组。如何在我的最后一个函数中声明一个日期而不是日期列表?

编辑:通过创建两个接口找到了一个可行的解决方案:

interface AjaxResponse {
    calendar: {
        dates: AjaxResponseDate[]
    },
    rights: string,
    listenerUrl: string
}

interface AjaxResponseDate {
    date: string,
    hours: {
        hour: string,
        id: number,
        status: string,
        client: {
            name: string,
            surname: string,
            email: string,
            phone: string,
            id: number
        }
    }
}

【问题讨论】:

    标签: arrays typescript object


    【解决方案1】:

    要获取数组中某项的类型,可以使用number的类型查询:

    function editDates(newDate: AjaxResponse['calendar']['dates'][number]) {
    }
    

    拥有 t 个接口的解决方案也是一种可能的解决方案,但如果需要,您可以保留单一类型。

    【讨论】:

    • 是的,两者都可以使用,但你的回答完全符合我的询问。谢谢
    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 2016-08-12
    • 2016-11-19
    • 2020-09-12
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2020-05-02
    相关资源
    最近更新 更多