Home > Enterprise >  How to create a function in typescript which takes array as an user input and how to find array leng
How to create a function in typescript which takes array as an user input and how to find array leng

Time:01-05

I need to create a function in typescript that takes array as an input that accept any type of array. and then calculate the number of elements present in it and return it.

I want a output like let if user input : ["cricket","football"] then output : 2

how to solve this this using typescript?

CodePudding user response:

you can use the generic type T to allow any type of array in parameter

arrayLength<T>(myArray:T[]): number {
    return myArray.length;
}

CodePudding user response:

You can check this tutorial out on how to pass an array to a function:>> https://www.tutorialspoint.com/typescript/typescript_passing_arrays_to_functions.htm

To calculate the length of an array, it'll be like this:

console.log(array.length);

Detailed documentation:>> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

  •  Tags:  
  • Related