首页 > 解决方案 > Typescript 在函数之前或类型声明之后编写的基因有什么区别?

问题描述

箭头函数的两种类型声明有什么区别?

export type Sort = <D>(r: Rows<D>, f: Field<D>, o: Order) => Rows<D>;
export type Sort<D> = (r: Rows<D>, f: Field<D>, o: Order) => Rows<D>;

标签: typescript

解决方案


功能方面没有区别,TS 编译器会强制你在不同的地方声明 D:

https://stackblitz.com/edit/typescript-yb3pjn?file=index.ts

interface Foo {
 valX: number
}

interface Bar {
 valY: string
}

interface Rows<D> {
 rows: D[]
}

interface Field<D> {
  value: D
}

type Order = 'asc' | 'desc'

export type SortA = <D>(r: Rows<D>, f: Field<D>, o: Order) => Rows<D>;
export type SortB<D> = (r: Rows<D>, f: Field<D>, o: Order) => Rows<D>;

const sortFunction: SortA = <Foo>(rows: Rows<Foo>, field: Field<Foo>, o: Order) => {
  return rows
}

const sortBFunction: SortB<Bar> = (rows: Rows<Bar>, field: Field<Bar>, o: Order) => {
  return rows
}

推荐阅读