Reputation: 551
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?
Upvotes: 4
Views: 661
Reputation: 249466
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
}
Upvotes: 8