鉴于此JavaScript函数:
function foo({ a, b, c = a + b }) {
return c * 2;
}
当我尝试用打字稿中的类型注释它时:
function foo({ a, b, c = a + b }: { a?: number, b?: number, c: number }): number {
return c * 2;
}
我得到错误:TS2532 Object is possibly undefined
这很有意义,因为我还没有告诉过它,a
并且b
在c
未指定时不是可选的。
但是,任何尝试指定此方法均无效:
function foo({ a, b, c = a + b }: { a: number; b: number; c: number }): number;
function foo({ c }: { c: number }): number {
return c * 2;
}
TS2371: A parameter initializer is only allowed in a function or constructor implementation.
function foo({ c }: { c: number }): number;
function foo({ a, b, c = a + b }: { a: number; b: number; c: number }): number {
return c * 2;
}
TS2394: This overload signature is not compatible with its implementation signature.
这对我来说没有意义,我看不出为什么TypeScript认为它们不兼容。
function foo({
a,
b,
c = a + b,
}: {
a: typeof c extends number ? void : number;
b: typeof c extends number ? void : number;
c: typeof a extends number ? void : typeof b extends number ? void : number;
}): number {
return c * 2;
}
TS2502: 'a' is referenced directly or indirectly in its own type annotation.
TS2502: 'c' is referenced directly or indirectly in its own type annotation.
鉴于TypeScript无法解决递归问题,这是有道理的。
有谁知道如何将此功能强类型化?
注意:我非常清楚您可以将原型本身更改为具有不同的参数结构,但是这样做会失败。
这是一个使用联合类型的命题:
type AB_Defined = {
a: number,
b: number,
c?: number,
}
type AB_Nullable = {
a?: never,
b?: never,
c: number,
}
type FunctionParams = AB_Defined | AB_Nullable
// here I need to cheat using a! and b! to tell it cannot be undefined
function foo({ a, b, c = a! + b! }: FunctionParams) {
return c * 2;
}
foo({ a: 3, b: 2 });
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句