函数接口中的意外类型推断

时间:2017-05-26 07:20:17

标签: typescript

TypeScript 2.3.3。

{
    interface F { <T extends string = string>(x: T): T }
    const f: F = x => 1; // test failed: an error was expected
}{
    interface F<T extends string = string> { (x: T): T }
    const f: F = x => 1; // test passed: an error as expected
}

有人可以解释一下这种行为吗?

1 个答案:

答案 0 :(得分:1)

您遇到的错误

interface F<T extends string> { (x: T): T }
const f: F = x => 1; // Error: Generic argument was expected

与函数返回number这一事实无关。

如果您实际使用以下类型抑制错误:

interface F<T extends string> { (x: T): T }
const f: F<any> = x => 1; // test failed: an error was expected

您可以看到为什么 第一个案例没有错误。通用推断为any,因此any => any

的函数可以轻松满足any => number
interface F { <T extends string = string>(x: T): T }
const f: F = x => 1; // No error cause `any` => `number` is valid for `any` => `any`