gpt4 book ai didi

typescript : enforce generics to have some keys compulsory

转载 作者:行者123 更新时间:2023-12-02 00:21:45 26 4
gpt4 key购买 nike

我希望下面的函数只接受 data 对象,前提是其中有 id 键。然后,想要从 data 访问 id

function someFuntion<T>(data : T){
const id = data['id'] //Error : Element implicitly has an 'any' type because type '{}' has no index signature.
}

这可能吗?

最佳答案

您需要为您的泛型类型参数添加一个约束:

function someFuntion<T extends { id: any}>(data : T){
let id = data['id']
id = data.id // also ok
}

关于 typescript : enforce generics to have some keys compulsory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55134178/

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