【问题标题】:Generics function in typescript can't find interface property打字稿中的泛型函数找不到接口属性
【发布时间】:2017-05-29 13:26:33
【问题描述】:

我正在尝试使用泛型在打字稿中创建以下函数,但它向我显示以下错误:

“'CustomerInterface' 类型上不存在属性 'id'” 这发生在:customer.id === +id

        getCustomer<CustomerInterface>(id: number | string){
            return this.getCustomers<CustomerInterface>('')
                .then(customers => customers.find(customer => customer.id === +id));
        }

接口定义:

export interface CustomerInterface {
    id: number
    name: string
    display_name: string
    address: string
    city: string
    phone_number: string
}

【问题讨论】:

  • 您可以添加错误的屏幕截图以及导致的行。还有你的 customer 对象是什么?

标签: angular generics typescript


【解决方案1】:

一段时间后,我找到了使用泛型约束 =P 的解决方案 应该是这样的:

getCustomer<T extends CustomerInterface>(id: number | string){
    return this.getCustomersCloseTo<T>('')
        .then(customers => customers.find(customer => customer.id === +id));
}

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 2021-11-13
    • 2017-09-26
    • 2019-03-12
    • 2023-02-22
    • 2021-05-10
    • 2021-02-15
    • 2018-12-27
    • 2021-12-30
    相关资源
    最近更新 更多