Bondowocopz
Bondowocopz

Reputation: 35

Extending type of function argument

I have function as follows:

async paginate(
    msg: Message,
    title: string,
    data: Array<any>,
    message: (
      currentData: any,
    ) => Promise<string | { title: string; description: string }>,
    perPage = 10,
  ): Promise<void> {
      // Function code here
  }

I can't determine the type of data, and it can be an array of any type.

I want to make currentData have the same type as data provided in the second argument. For example, if data i provided is an array of string, currentData should have a type of string, not any.

Upvotes: 2

Views: 650

Answers (1)

Nishant
Nishant

Reputation: 55866

You want to use generics here:

async paginate<T>(
    msg: Message,
    title: string,
    data: Array<T>,
    message: (
      currentData: T,
    ) => Promise<string | { title: string; description: string }>,
    perPage = 10,
  ): Promise<void> {
      // Function code here
  }

Essentially this tells Typescript that data is an array of type T, and and the message takes a parameter named currentData which also has type T, where type T will be decided later during the function call. So, if your data type is string, you call it like this:

paginate<string>(
 // parameters
)

and when data is something complicated, say, of type Person defined as type Person = {name: string, age: number}, you could call the same function with the new type argument like this:

paginate<Person>(
...
)

And your data and currentData will be validated against Person type.

Here is a short example

type Message = number;
function paginate<T>(
    msg: Message,
    title: string,
    data: Array<T>,
    message: (
      currentData: T,
    ) => Promise<string | { title: string; description: string }>,
    perPage = 10,
  ): Promise<void> {
    return Promise.resolve();
  }

// OK
paginate(1, '123', [1,2,3], (a: number) => Promise.resolve('something'));
// OK
paginate(1, '123', ['a','2','3'], (a: string) => Promise.resolve('something'));

// Error
paginate(1, '123', ['a','2','3'], (a: number) => Promise.resolve('something'));
// Error
paginate(1, '123', [1,2,3], (a: string) => Promise.resolve('something'));

TSPlayground link

Upvotes: 1

Related Questions