I want the below function should only accept data
object if there is id
key in it. And then, want to access id
from data
.
function someFuntion<T>(data : T){
const id = data['id'] //Error : Element implicitly has an 'any' type because type '{}' has no index signature.
}
Is it possible?
You need to add a constraint to your generic type parameter:
function someFuntion<T extends { id: any}>(data : T){
let id = data['id']
id = data.id // also ok
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With