简体   繁体   English

如何使返回类型以可选参数为条件

[英]How to make return type conditional on optional param

So I have a function like this所以我有一个像这样的 function

export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: T): ??? {
  const value = dict[key] as T | undefined;
  return value ?? fallback;
}

It would be nice that if I was calling myFunc that if the fallback was passed, it knew that undefined is no longer a possibility for the return type.如果我调用 myFunc 并且如果通过了回退,它知道 undefined 不再是返回类型的可能性,那就太好了。 For instance例如

const x = myFunc<boolean>({}, "hello") // should be typed as boolean | undefined

const y = myFunc<boolean>({}, "hello", false) // should be typed as boolean only but is typed as boolean | undefined

Right now, the return type is always T |现在,返回类型始终是 T | undefined, even if I pass in a fallback.未定义,即使我通过后备。 Is there a way to handle this conditional return type based on the presence of an optional param?有没有办法根据可选参数的存在来处理这种条件返回类型?

This is function overloading.这是 function 过载。 So we can define our 2 variants, 1 where fallback is defined and typed as T and another where fallback is specifically undefined.所以我们可以定义我们的 2 个变体,1 个定义了 fallback 并将其类型化为 T,另一个定义了 fallback 未定义。 When defined we get back T and when undefined we get back T |定义时返回 T,未定义时返回 T | undefined.不明确的。 And, once we do that, you should also be able to remove the as T cast as well.而且,一旦我们这样做了,您也应该能够删除 as T 演员。

export function myFunc<T>(dict: Record<string, T>, key: string, fallback: T):T;
export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: undefined):T | undefined;
export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: T): T | undefined {
const value = dict[key] as T | undefined;
 return value ?? fallback;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM