[英]Typescript function return type based on optional arguments
How can bad types be resolved?如何解决坏类型?
interface X<T> {
abc:T
}
declare function deepLock<Obj extends Record<string, any>,>(obj: Obj): X<Obj>;
declare function deepLock<Obj extends Record<string, any>,>(obj: Obj, options: {}): X<Obj>;
declare function deepLock<
Obj extends Record<string, any>,
Action extends "freeze" | "seal" | "preventExtensions",
Options extends { action?: Action }
>(obj: Obj, options?: Options): Action extends 'freeze' ? X<Obj> : Obj
// ok
const x = deepLock({}) // expect X<{}>
const x2 = deepLock({}, {}) // expect X<{}>
// need to be fixed
const x3 = deepLock({}, {action: 'freeze'}) // expect X<{}>
const x4 = deepLock({}, {action: 'seal'}) // expect Obj
const x5 = deepLock({}, {action: 'preventExtensions'}) // expect Obj
So you just need to adjust your function definition very slightly to:所以你只需要稍微调整你的函数定义:
declare function deepLock<
Obj extends Record<string, any>,
Action extends "seal" | "preventExtensions" | "freeze",
>(obj: Obj, options?: { action?: Action }): 'freeze' extends Action ? X<Obj> : Obj;
The problem you are facing is that Action
is extending "seal" | "preventExtensions" | "freeze"
您面临的问题是
Action
正在扩展"seal" | "preventExtensions" | "freeze"
"seal" | "preventExtensions" | "freeze"
"seal" | "preventExtensions" | "freeze"
and so by definition Action extends "freeze"
will always be true as it always extends that. "seal" | "preventExtensions" | "freeze"
,因此根据定义, Action extends "freeze"
将始终为真,因为它总是扩展它。
So in order to correctly narrow the types you have to do "freeze" extends Action
which will only ever be true for one of the three possibilities for Action.因此,为了正确缩小类型,您必须执行
"freeze" extends Action
,这仅适用于 Action 的三种可能性之一。
Hope that makes sense希望这是有道理的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.