how to define a type to check that an object contains an id key?
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.
Answer
Yes, in fact you need to create a dictionary type. More info on here.
>>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;
}