How do I implement the listToList
function below to meet the following criteria:
- The
listItem
and return type must be limited to onlystring
orundefined
, no other types allowed - If
listItem
isundefined
, then the function should returnundefined
- If
listItem
is astring
, then it should return a differentstring
In this scenario, there are two lists, and sometimes there is an item from one list, which needs to match the item at the same index in the other list. However, if listItem
is undefined
, the method should simply return undefined
.
function listToList<T extends string | undefined>(listItem: T, startList: string[], endList: string[]): T {
if (listItem === undefined) {
return listItem;
}
const index = startList.indexOf(listItem);
if (index === -1) {
throw `Item not in list!`;
}
return endList[index];
}
An error is encountered:
Type 'string' is not assignable to type 'T'.
'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | undefined'.
It is ensured that the type will always be a string by checking for undefined
. TypeScript recognizes this as well, evidenced by no complaints when calling .indexOf(listItem)
a few lines earlier.
Why isn't type guarding effective here? What might have been done incorrectly, and how can this problem be addressed?
Edit: A working JavaScript implementation can be found here, the issue lies within the Typescript portion.