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

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);   

推荐答案

您可以使用函数重载来完成此操作:

type TestReturnType<T> = T extends string ? number : string;

function test(value: string): TestReturnType<string>;
function test(value: number): TestReturnType<number>;
function test<T>(value: T): TestReturnType<string | number> {
    if (typeof value === 'string') {
        return 1;
    } else {
        return '1';
    }
}

const res1 = test('String');   // res1: number
const res2 = test(13123);      // res2: string

请注意,

  • 如果省略重载,则res1res2的类型都为string | number
  • 您可以删除test的type参数并将其声明为function test(value: any)

Typescript相关问答推荐

如何在ts中使用函数重载推断参数类型

将值添加到具有不同类型的对象的元素

如何使用类型谓词将类型限制为不可赋值的类型?

对未到达受保护路由的路由环境做出react

用于验证字符串变量的接口成员

如何在处理数组时缩小几个派生类实例之间的类型范围?

路由链接始终返回到

如何避免推断空数组

为什么ESLint会抱怨函数调用返回的隐式`any`?

如何将TS泛型用于react-hook-form接口?

React router 6(数据路由)使用数据重定向

在抽象类属性定义中扩展泛型类型

扩展对象的此内容(&Q;)

在打印脚本中将对象类型转换为数组

如何以类型安全的方式指定键的常量列表,并从该列表派生所挑选的接口?

如何实现允许扩展泛型函数参数的类型

Typescript 是否可以区分泛型参数 void?

我可以使用对象属性的名称作为对象中的字符串值吗?

如何使用动态生成的键和值定义对象的形状?

如果父级被删除或删除,如何自动删除子级?