流函数表达式的泛型类型(箭头函数) [英] flow generic type for function expression (arrow functions)

查看:1380
本文介绍了流函数表达式的泛型类型(箭头函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常会尝试将流程功能类型与其实现分开。我写的时候它的可读性略高一些:

  type Fn = string =>串; 
const aFn:Fn = name => `hello,$ {name}`;

而不是:

  const aFn =(name:string):string => `hello,$ {name}`; 

当使用泛型时,我们可以这样写:

  const j =< T>(i:T):T =>一世; 

const jString:string = j('apple'); //√
const jNumber:number = j(7);但是,如何将这种类型与函数表达式分开?


$ b $ / code>


$ b

  type H< T> =(输入:T)=>吨; 
const h:H * = i =>一世; // - >什么应该去'*'?

const hString:string = h('apple'); // X错误
const hNumber:number = h(7); // X错误

* 任何都可以工作,但那不是我想要的。



在haskell中,这是一个非问题:

  identity :: a  - > a 
identity a = a

identitya-string//√
identity 666 //√

请参阅 flow.org/try

解决方案

所以我注意到如果我使用有界的泛型,它会工作:

  type H< T> =< T:*>(输入:T)=>吨; 
const h:H * = i =>一世;

const a:string = h('apple'); //√
const b:number = h(7); //√
const c:{} = h({nane:'jon'}); //√

不要问我为什么。


I usually try to keep flow function types separate from their implementation. It's a slightly more readable when I write:

type Fn = string => string;
const aFn: Fn = name => `hello, ${ name }`;

rather than:

const aFn = (name: string): string => `hello, ${ name }`;

When using generic types we can write:

const j= <T>(i: T): T => i;

const jString: string = j('apple'); // √
const jNumber: number = j(7);       // √

But how can I separate this type from a function expression?

type H<T> = (input: T) => T;
const h:H<*> = i => i;              // --> WHAT SHOULD GO FOR '*'?

const hString: string = h('apple'); // X error
const hNumber: number = h(7);       // X error

What should be used for *? any would work but that's not what I want.

In haskell this is a non-issue:

identity :: a -> a
identity a = a

identity "a-string" // √
identity 666        // √

See flow.org/try

解决方案

So I have noticed that if I use bounded generics, it'll work:

type H<T> = <T: *>(input: T) => T;
const h:H<*> = i => i;

const a: string = h('apple');      // √
const b: number = h(7);            // √
const c: {} = h({ nane: 'jon' });  // √

Don't ask me WHY.

这篇关于流函数表达式的泛型类型(箭头函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆