1

I am facing a problem when migrating my JSX code to TSX as follows:

TS error message

This is the interface:

interface IParams {
  user_id: string;
  first: number;
  started_at: Date;
  ended_at: Date;
}

This code works as entended in JSX and Google does not seem to have a definite answer for this, how could I fix this somehow ?

Thank you!

NVH

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
nvh
  • 95
  • 1
  • 6

2 Answers2

1

You could make it work by defining the type of key to be explicit i.e.

let key: keyof IParams;
for (key in params) {
  url.searchParams.set(key, params[key]);
}

Alternatively if all you are trying to do is get the value you could do so by using Object.entries which would look like:

for (const [key, value] in Object.entries(params)) {
  url.searchParams.set(key, value);
}

// or if you wanted to use forEach

Object.entries(params).forEach(([key, value]) => {
  url.searchParams.set(key, value);
});
zecuria
  • 728
  • 4
  • 9
0

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)
msbit
  • 4,152
  • 2
  • 9
  • 22