英文:
Typescript function that accepts generic as argument but returns multiple types
问题
我有一个非常简单的函数,接受一个可以是任何类型的单一参数。我只检查这个参数是否已定义,但如果未定义,它会返回一个类型为 HttpError(来自 SvelteKit)的错误。
function safe<T>(arg: T): T {
return arg ?? HttpError;
}
我试图使它在参数未定义的情况下同时返回参数类型和 HttpError。我尝试使用泛型,但我得到了这样的消息:“'HttpError' 无法分配给类型 'T'。'T' 可以用任意类型来实例化,可能与 HttpError 无关”。是否有办法解决这个问题?我试图返回一个联合类型,但不起作用。
英文:
I have a very simple function that accepts a single parameter that can be of any type. I only check if this parameter is defined or not, but if it isn't, it returns an error if type HttpError (from SvelteKit).
function safe<T>(arg: T): T {
return arg ?? HttpError;
}
I'm trying to make it return both the argument type and the HttpError in the case that the argument isn't defined. I tried with generics, but I get the message that 'HttpError is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to HttpError'.
Is there any way to work around this? I tried to make a union return but it doesn't work.
答案1
得分: 2
问题可能是你返回了一个类,而应该返回一个实例。即。
function safe<T>(arg: T) {
// error creates an `HttpError`
return arg ?? error(400, 'Bad Request');
}
此外,无需显式指定返回值类型,它会自动推断。在这种情况下,编译器还会添加 null 检查并推断:
HttpError | NonNullable<T>
根据函数的使用方式,你也可以考虑直接抛出错误。
顺便说一下,如果你想要明确的返回类型以增加清晰度,在 VS Code 中,你可以先编写函数而不带类型,然后应用重写快速修复 "推断函数返回类型",它会为你添加正确的类型。
英文:
The issue is probably that you are returning a class when you should be returning an instance. I.e.
function safe<T>(arg: T) {
// error creates an `HttpError`
return arg ?? error(400, 'Bad Request');
}
There also is no need to type the return value explicity, it will be inferred automatically. In this case the compiler will also add the null check and infer:
HttpError | NonNullable<T>
You also might want consider just throwing the error, depending on how the function is to be used.
By the way, if you want the explicit return type for clarity, in VS Code you can just write the function without the type first and then apply the rewrite quick fix "Infer function return type" and it will add the correct type for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论