2017-05-26 53 views
1

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

我得到在这两种情况下的错误..因为你不能一个号码分配给一个字符串。类型F的函数(在这两种情况下)都会返回一个字符串。 – toskv

+0

@toskv,我在第二个(TS 2.3.3)中得到一个错误。顺便说一下,我简化了这个例子。 – dizel3d

+0

我用简化的方法试过了,它是一样的。 – toskv

回答

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`