I'm currently working on a function where the return type is determined by the input values, but I'm finding that typescript is requiring me to use the as
keyword to address the issue I'm facing. Is there a more graceful way to handle this and avoid using as
?
type TestReturnType<T> = T extends string ? number : string;
const test = <T,>(value: T): TestReturnType<T> => {
if (typeof value === 'string') {
return 1 as TestReturnType<T>; // ?
} else {
return '1' as TestReturnType<T>; // ?
}
};
const res1 = test('String');
const res2 = test(13123);