Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript union as function parameter

I have an app where I use a json structure to define the columns of a table.

Each column has a key and label property and an optional transformFunc property that takes a function that transforms the data to be displayed in the column.

This is the type for Column:

type Column = {
  key: string
  label: string
  transformFunc?: (value: string | number | Date) => string
};

transformFunc either takes a string, number or Date as an argument. However, I'm not able to properly type it this way:

const col: Column = {
  key: 'date',
  label: 'Date',
  transformFunc: (value: string) => value.substring(0, 5)  // TS2322: Type '(value: string) => string' is not assignable to type '(value: string | number | Date) => string'
}

How can I solve this?

I looked into generics but I don't see how to do this.

like image 849
Danny Moerkerke Avatar asked Apr 16 '26 18:04

Danny Moerkerke


1 Answers

In generic way

type Column<T extends string | number | Date> = {
  key: string
  label: string
  transformFunc?: (value: T) => string
};

const col: Column<string> = {
  key: 'date',
  label: 'Date',
  transformFunc: (value) => value.substring(0, 5)
}
like image 71
dhaker Avatar answered Apr 19 '26 07:04

dhaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!