简体   繁体   English

Typescript generics 返回类型问题

[英]Typescript generics return type issues

I use typescript generics in my project but it seems not work well.我在我的项目中使用 typescript generics 但它似乎效果不佳。

example:例子:

interface Test<T, P> {
  a?: (v: T) => P
  b?: (v: P) => void
}

const fn1 = <T, P>(_config: Test<T, P>) => {}

fn1({
  a: (p) => 1,
  b: (p) => {},
})

I think params 'a' type just like:我认为params 'a'类型就像:

Test<unknown, number>.a?: ((v: unknown) => number) | undefined

But, actually:但实际上:

Test<unknown, unknown>.a?: ((v: unknown) => unknown) | undefined

I do not know why, someone can help me?我不知道为什么,有人可以帮助我吗? Thanks.谢谢。

Since you are not defining the type on this line: b: (p) => {}由于您没有在此行定义类型: b: (p) => {}

Then TS cannot infer the type of P, even though you return it in the above definition for a .然后 TS 无法推断 P 的类型,即使您在上述a的定义中返回它。

This is because in a union an unknown absorbs everything.这是因为在联合中,未知吸收了一切。

For P in (a) TypeScript infers a type of "number", but then for P in (b) it infers a type of "unknown", just as it does for T in (a).对于 (a) 中的 P,TypeScript 推断出一种“数字”,但是对于 (b) 中的 P,它推断出一种“未知”,就像它对于 (a) 中的 T 所做的那样。

Therefore, P results in a "number | unknown" (not "number | undefined" as you expected), which results in just "unknown".因此,P 会导致“数字 | 未知”(不是您预期的“数字 | 未定义”),这只会导致“未知”。

If you refer to the TypeScript docs here , you'll find:如果您在此处参考 TypeScript 文档,您会发现:

// In a union an unknown absorbs everything // 在联合中,未知数吸收一切

type P = unknown | P 型 = 未知 | number;数字; // unknown // 未知

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

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