I'm refactoring a JS code into TS (actually jsx/tsx) and I'm facing a problem with functions.
To simplify the issue... let's suppose I get this function "checkIt", which can receive a string or number as parameter and returns a boolean.
This is the JS function:
const FIRST_ROW = 'Initial';
const SECOND_ROW = new Set([1, 2, 3, 4]);
const checkIt = id => {
if (FIRST_ROW.includes(id) || SECOND_ROW.includes(id)) {
return true;
}
return false;
}
Here is my trial... (as I'm learning TS, I like to declare inferred variables to be consistent)
const FIRST_ROW: string = 'Initial';
const SECOND_ROW: Set<number> = new Set([1, 2, 3, 4]);
const checkIt = <T,>(id: T): boolean => {
if (FIRST_ROW.includes(id) || SECOND_ROW.includes(id)) {
return true;
}
return false;
}
This gets me an error on my my "id" references inside the function: Argument of type 'T' is not assignable to parameter of type 'string' (or 'number'). I've tried using function expression, the Union string | number (as explained here), different forms of writing Generics, and Overloads (like here and I just can't make it work.
Any help here?? Thank you!