[英]How to define the return type of a function according to the input parameters with Typescript?
I have a function with an object as argument:我有一个 function 和一个 object 作为参数:
// Types
type Params = {
first: string;
second: number;
third?: boolean;
};
type FunctionA = (params: Params) => { [key: string]: any } | void;
// Function
const functionA: FunctionA = params => {
// ... do something
if (params.third) {
return {one: "object"}
}
};
So basically, what I want to achieve is that if third
has been submitted, I want that the function return type is {[key: string]: any}
.所以基本上,我想要实现的是,如果已经提交了
third
,我希望 function 返回类型是{[key: string]: any}
。 If third
is not submitted, I want it to be never
.如果
third
没有提交,我希望它是never
。
I have found solutions where the return type of a function changes according to the argument which has been returned but nothing, if the object is an argument and with a return type which is different from the argument type.我找到了解决方案,其中 function 的返回类型根据已返回的参数而变化,但如果 object 是一个参数并且返回类型与参数类型不同。
Is this even possible?这甚至可能吗?
Thanks!谢谢! Any help appreciated!
任何帮助表示赞赏!
You could use function overloads .您可以使用function 过载。
LE: After reading the question better I think this is what you want: LE:更好地阅读问题后,我认为这就是您想要的:
type Params = {
first: string;
second: number;
third?: boolean;
};
function A(params: Omit<Params, "third">): void
function A(params: Required<Params>): { [key: string]: any }
function A(params: Params): { [key: string]: any } | void {
if (params.third === undefined) {
return
}
return {...params}
}
Again, you are overloading the function, but this time you are declaring one without third
in the params and another where all fields are required, including third
.同样,您正在重载 function,但这次您在参数中声明一个没有
third
,而另一个是所有字段都需要的地方,包括third
。
You can see this in action in this playground .你可以在这个操场上看到这一点。
You can declare 2 functions with 2 and 3 params and then implement it.您可以使用 2 和 3 个参数声明 2 个函数,然后实现它。 Something similar to this:
与此类似的东西:
function A (first: string, second: string, third: boolean): {[key: string]: any}
function A (first: string, second: string): never
function A (first: string, second: string, third?: boolean) {
if (third === undefined) {
throw new Error("error message")
}
return {first, second, third}
}
Now your IDE or any code helper should know that if you pass 2 params you have a return type and if you pass 3 another.现在您的 IDE 或任何代码助手应该知道,如果您传递 2 个参数,则您有一个返回类型,如果您传递 3 个另一个参数。
Note: I don't see a valid reason for returning never
when not passing the third argument.注意:当不传递第三个参数时,我没有看到
never
返回的正当理由。 Is almost like you want to make the 3rd one mandatory and not optional.几乎就像你想让第三个强制性而不是可选的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.