Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define a type to check that an object contains an id key?

Tags:

typescript

Is there a way to define an interface so that it can contain any number of keys but must contain the id key?

interface HasId{
   id: number
}

Something like this can be defined but it will output an error if there is another key in the data structure.

like image 977
zcaudate Avatar asked Oct 27 '25 03:10

zcaudate


1 Answers

Yes, in fact you need to create a dictionary type. More info on Advanced Types.

interface HasId {
    id: number;
    [key: string]: any;
}

You can also make it more generic like

interface IDictionary<T> {
    [key: string]: T;
}

interface HasId extends IDictionary<number> {
    id: number;
}
like image 187
jank Avatar answered Oct 30 '25 03:10

jank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!