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
}
有人可以解释一下这种行为吗?
答案 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`