两个通用函数,都传入相同的参数但求值不同,为什么

Two generic functions, both passed in the same parameter but evaluated differently, why

我有以下泛型函数代码:

type Bar<T> = {bar: T}

function test1<T>(arg: T extends {foo: number} ? T : never): void {}
function test3<T>(arg: T extends {foo: number} ? Bar<T> : never): void {}

当我打电话给他们时:

test1({foo: 23}); // Good!
test3({foo: 23}); // Type 'number' is not assignable to type 'never'.

我很困惑,我的意思是 test1(...)test3(...) 不应该评估 arg: T extends {foo: number} 的类型条件为真吗?我的意思是它们将完全相同的参数传递给函数并且它们对类型具有相同的评估条件。

换句话说,为什么 test3({foo:23}) 属于类型的 never 值而不是 Bar<T>?我还预计 test3({foo:23}) 会失败,但会出现一条错误消息,提示 {bar: number},为什么错误消息会抱怨 never 方面?

I get confused, I mean shouldn't both test1(...) and test3(...) evaluating type condition of arg: T extends {foo: number} to be true?

test3 中,您说过当 T extends {foo: number} 时参数将是 Bar<T>。所以它会期望 {bar: {foo: number}} 因为 Bar<T>{bar: T}。由于您传递的内容无法匹配 Bar<T>,因此使用 never

如果你传递给它你所说的它应该接收的东西,它工作得很好:

test3({bar: {foo: 23}}); // Good!

Playground link