🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
大多数时候,类型自己被推断,然后可以被统一为一个预期的类型。然而在一些地方,一个预期的类型可能被用来影响推断。然后我们讨论自上而下的推断。 > Most of the time,types are inferred on their own and may then be unified with an expected type. In a few places,however,an expected type may be used to influence inference. We then speak of top-down inference. **预期类型** >[warning] 定义:预期类型 预期的类型在表达式的类型在它被类型化之前已知的时候出现,例如,因为表达式被看作一个函数调用。它们可以影响这个表达式的类型化,通过所谓的自上而下推断(第3.6.1节)。 >[warning] Definition: Expected Type Expected types occur when the type of an expression is known before that expression has been typed, e.g. because the expression is argument to a function call. They can influence typing of that expression through what is called top-down inference (3.6.1). 一个很好的例子是混合类型的数组。如在 Dynamic(第2.7节)中提到的,编译器拒绝[1,"foo"]因为它不能确定元素的类型。使用自上而下的推断,这个问题可以被克服: > A good example are arrays of mixed types. As mentioned in Dynamic (Section 2.7), the compiler refuses [1, "foo"] because it cannot determine an element type. Employing top-down inference, this can be overcome: ~~~ class Main { static public function main() { var a:Array<Dynamic> = [1, "foo"]; } } ~~~ 这里,编译器知道当类型化 [1,"foo"],预期的类型是 Array<Dynamic>,所以元素类型是 Dynamic 。和通常的合一行为不同,编译器会尝试(并失败)去确定一个通用类型(第3.5.5节),个别的元素不利于类型化会被统一为 Dynamic。 > Here,the compiler knows while typing [1, "foo"] that the expected type is Array<Dynamic>, so the element type is Dynamic. Instead of the usual unification behavior where the compiler would attempt (and fail) to determine a common base type (3.5.5), the individual elements are typed against and unified with Dynamic. 在构建泛型类型参数(第3.3.1节)被引入的时候,我们看到了另一个自上而下推断的有趣用法 > We have seen another interesting use of top-down inference when construction of generic type parameters (3.3.1) was introduced: ~~~ typedef Constructible = { public function new(s:String):Void; } class Main { static public function main() { var s:String = make(); var t:haxe.Template = make(); } @:generic static function make<T:Constructible>():T { return new T("foo"); } } ~~~ 显式的类型 String是 被haxe.Template在这里使用的,来确定make的返回类型。这是因为方法调用为 make(),所以我们知道返回类型会分配到变量。利用这个信息,可以分别绑定 unknown 类型 T到 String和 haxe.Template 。 > The explicit types String and haxe.Template are used here to determine the return type of make. This works because the method is invoked as make(),so we know the return type will be assigned to the variables. Utilizing this information, it is possible to bind the unknown type T to String and haxe.Template respectively.