Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : enforce generics to have some keys compulsory

Tags:

typescript

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?

like image 481
Sanket Patel Avatar asked Sep 20 '25 01:09

Sanket Patel


1 Answers

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 
}
like image 197
Titian Cernicova-Dragomir Avatar answered Sep 23 '25 10:09

Titian Cernicova-Dragomir