typescript - 基于参数属性的打字稿函数返回类型
问题描述
如何为函数创建正确的类型,以便根据其输入参数的属性,在调用此函数时获得正确的返回类型?
这是我目前得到的,但两个电话都给了我相同的boolean | boolean[]
类型 when fn({ a: 42 })
should give meboolean
和fn({ b: 'hi' })
should give me boolean[]
。
type ParamType = { a?: number, b?: string }
type ReturnType<T> =
T extends 'a' ? boolean :
T extends 'b' ? boolean[] :
never[]
function fn<T extends keyof ParamType>(arg: ParamType) {
if (arg.a) {
return true as ReturnType<T>;
}
else if (arg.b) {
return [true, false] as ReturnType<T>;
}
else return [] as ReturnType<T>;
}
fn({ a: 42 }); // function fn<"a" | "b">(arg: ParamType ): boolean | boolean[]
fn({ b: 'hi' }); // function fn<"a" | "b">(arg: ParamType ): boolean | boolean[]
a
另外,我不是必须在类型中定义文字对象属性和两次的超级粉丝b
,如果有更好的方法来做到这一点,请指出正确的方向。
解决方案
您的问题很不寻常,但首先:使用in
运算符检查密钥是否存在。其次:如果 a 和 b 都被声明,即使是可选的,这也没有效果。使用联合。最后,如果你声明的类型参数没有分配给参数,在大多数情况下,它是没有效果的。
尝试这个:
type ParamType = {a: number | string;} | {b: number | string;};
type MyReturnType<T> =
T extends 'a' ? boolean :
T extends 'b' ? boolean[] :
never[];
function fn<T extends ParamType>(arg: T) {
if ("a" in arg) {
return true as MyReturnType<keyof T>;
}
else if ("b" in arg) {
return [true, false] as MyReturnType<keyof T>;
}
else return [] as MyReturnType<keyof T>;
}
fn({a: 42});
/*function fn<{
a: number;
}>(arg: {
a: number;
}): boolean*/
fn({b: 'hi'});
/*function fn<{
b: string;
}>(arg: {
b: string;
}): boolean[]*/
有关工会,请参阅https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#unions和https://www.typescriptlang.org/docs/handbook/release-notes/ typescript-2-7.html#type-guards-inferred-from-in-operator用于in
类型保护。
推荐阅读
- python - 如何使显示在 3 列网格中的两个小部件之间的间距在 tkinter 中相等?
- flutter - Flutter web 中的 Firebase Phone 身份验证
- ruby-on-rails - 如何从 Rails 中的 npm 包加载 svg?
- .net-core - EF Core 3.18 从相关表中获取总和和计数
- mysql - 非过程语句中的 MySQL 条件检查
- eloquent - Laravel eloquant belongsToMany 获取记录属于关系
- reactjs - 如何在列内的渲染中传递函数(范围问题)
- python-3.x - 比较 datetime.now 和 EC2 映像 creation_date 的问题
- http - 我无法更改 NextJS 项目中的 HTTP 标头
- java - 尝试使用 jGRASP 进行编译时出现错误,不知道如何修复