Sanket Patel
Sanket Patel

Reputation: 551

Typescript : enforce generics to have some keys compulsory

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

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Related Questions