TypeScript:基于参数的函数返回类型,无需重载 [英] TypeScript: function return type based on argument, without overloading
本文介绍了TypeScript:基于参数的函数返回类型,无需重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以根据参数返回函数的类型?
Is it possible to return a function's type based on an argument?
我看到了 基于字符串文字类型参数的变量返回类型,但它使用重载.在这里,我有 100 多种类型,所以我不想做重载.
I saw Variable return types based on string literal type argument, but it uses overloading. Here, I have 100+ types, so I do not want to do overloading.
interface Registry {
A: number,
B: string,
C: boolean,
// ... 100 more types like this
}
function createType<T = Registry[typeof myType]>(myType: keyof Registry, value: any): T {
// do some magic
// ...
return value;
}
const a = createType('A', 2); // Expected type: number. Actual: error above
推荐答案
你可以做到,但是你需要一个类型参数来捕获传入的参数.使用这个新的类型参数你可以索引到你的 Registry
得到你想要的类型:
You can do it, but you will need a type parameter to capture the argument passed in. With this new type parameter you can index into your Registry
to get the type you want:
interface Registry {
A: number,
B: string,
C: boolean
}
function createType<K extends keyof Registry>(type: K, value: Registry[K]): Registry[K] {
return value;
}
const a = createType('A', 2); // ok
const b = createType('B', 2); // err
这篇关于TypeScript:基于参数的函数返回类型,无需重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文