gpt4 book ai didi

javascript - 函数表达式的流通用类型(箭头函数)

转载 作者:可可西里 更新时间:2023-11-01 01:52:08 25 4
gpt4 key购买 nike

我通常会尝试将流函数类型与其实现分开。当我写的时候,它的可读性稍微好一点:

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

而不是:

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

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

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

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

但是我怎样才能将这种类型与函数表达式分开呢?

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

*应该使用什么? any 可以,但这不是我想要的。

在 haskell 中这不是问题:

identity :: a -> a
identity a = a

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

参见 flow.org/try

最佳答案

所以我注意到如果我使用 bounded generics ,它将起作用:

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' }); // √

不要问我为什么。

关于javascript - 函数表达式的流通用类型(箭头函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46596235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com