如何输入字典传递样式?

问题描述 投票:0回答:1

我知道TS不支持更高种类的类型。对于没有HKT和类型类的语言,可以使用字典传递样式:

const map = ({map}) => f => tx => map(f) (tx);

const arrMap = f => xs => xs.map(f);

const id = x => x;

const main = map({map: arrMap}) (id);

console.log(main([1,2,3]));

如何在TS中输入?

const map = <A, B, C>(dict: {map: (f: (x: A) => B) => (tx: C) => C}) => (f: (x: A) => B) => (tx: C) =>
  dict.map(f) (tx);

const id = <A>(x: A) => x;

const arrMap = <A, B>(f: (x: A) => B) => (xs: A[]) => xs.map(f);

map({ map: arrMap }) (id) ([1, 2, 3]); // type annotation?

可以避免类型注释吗?如果没有,它将是什么样?

typescript typeclass higher-kinded-types
1个回答
0
投票

我将“地图”更改为“ mapFn”,因为tslint中出现“无阴影变量”的错误]

type IdType = (param: number) => number;
type ArrMapType = (f: IdType) => (xs: number[]) => number[];
type MapFnType = (params: { map: ArrMapType }) => (f: IdType) => (tx: number[]) => number[];

const mapFn: MapFnType = ({ map }) => f => tx => map(f)(tx);

const arrMap: ArrMapType = f => xs => xs.map(f);

const id: IdType = x => x;

const main = mapFn({ map: arrMap })(id);

console.log(main([1, 2, 3]));
© www.soinside.com 2019 - 2024. All rights reserved.