我试图根据输入值正确设置函数的返回类型,然后typescript强迫我使用as
keyword来解决我遇到的问题.
有没有办法避免这种情况,有没有一个优雅的解决方案?
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);