I am a beginner in TypeScript and I'm struggling to find the right combination of search terms to solve my issue. It seems like using a type condition could be helpful, but I still need to grasp how they function.
My goal is to pass a function that performs some sort of manipulation. If the function returns a specific type, then I would like to enclose it in a box; otherwise, return the original value.
For example:
class Box<T> {
value: T;
constructor(value: T) {
this.value = value;
}
}
function wrapIfString<T, TResult>(fn: (value: T) => TResult, value: T):
TResult extends string ? Box<string> : TResult {
const result = fn(value);
if (value instanceof String) {
return new Box<string>(result);
}
return result;
}
However, this code does not compile. Can this be achieved in TypeScript?