To allow type safe indexing you can add an index signature with the string
key type to the type. A similar question can be found here, and for IParams
, it would look something like:
interface IParams {
user_id: string;
first: number;
started_at: Date;
ended_at: Date;
[key: string]: string | number | Date;
};
or using indexed access types in concert with keyof
(as in the linked question):
interface IParams {
user_id: string;
first: number;
started_at: Date;
ended_at: Date;
[key: string]: IParams[keyof IParams];
};
which would cover the situation where more fields are added to the type.
Altogether, the following compiles and runs fine for me:
interface IParams {
user_id: string;
first: number;
started_at: Date;
ended_at: Date;
[key: string]: IParams[keyof IParams];
};
const params: IParams = {
user_id: 'user_id',
first: 0,
started_at: new Date(),
ended_at: new Date()
};
for (const key in params) {
console.log(`${key} = ${params[key]}`);
}
with the following output:
user_id = user_id
first = 0
started_at = Tue Aug 31 2021 16:08:24 GMT+1000 (Australian Eastern Standard Time)
ended_at = Tue Aug 31 2021 16:08:24 GMT+1000 (Australian Eastern Standard Time)