【发布时间】:2017-07-21 00:46:45
【问题描述】:
我一直在阅读有关泛型的文章,并想了解泛型在流程中的工作原理。
https://flow.org/en/docs/types/generics/#toc-function-types-with-generics
我对使用流检查函数式编程的函数签名的想法特别感兴趣。
但是我不明白为什么以下方法不起作用:
当我尝试时
/* @flow */
const identity = (c) => c;
(identity: <T>(T) => T); // force flow to typecheck
然后Flow返回错误:
3: const identity = (c) => c;
^ T. This type is incompatible with
5: (identity: <T>(T) => T);
^ some incompatible instantiation of `T`
我会认为因为 c 始终是 c 并且没有被变异,所以它的类型必须与模式匹配?
问:如何表示函数必须返回与第一个参数相同的类型?
补充示例
即使我尝试使用类型别名,它似乎也不起作用。
/* @flow */
type ReturnsSameTypeAsFirstParam = <T>(T) => T;
const identity:ReturnsSameTypeAsFirstParam = (c) => c;
然后我得到:
4: const identity:ReturnsSameTypeAsFirstParam = (c) => c;
^ T. This type is incompatible with
4: const identity:ReturnsSameTypeAsFirstParam = (c) => c;
^ some incompatible instantiation of `T`
编辑:尝试澄清
我主要热衷于为函数提供一种类型作为参数,并了解如何以多态方式使用它们。
也许这是我尝试键入的内容的更清晰示例:
/* @flow */
type Transformer = <T>(T)=>T;
function transformAGivenThing(transform:Transformer, thing:*) {
return transform(thing);
}
function transformAString(str:string):string {
return str.toUpperCase();
}
transformAGivenThing(transformAString, 'thing');
这会在我运行流程时导致这些错误:
3: type Transformer = <T>(T)=>T;
^ T. This type is incompatible with the expected param type of
9: function transformAString(str:string):string {
^ string
9: function transformAString(str:string):string {
^ string. This type is incompatible with the expected param type of
13: transformAGivenThing(transformAString, 'thing');
^ some incompatible instantiation of `T`
【问题讨论】:
标签: javascript generics flowtype