DEV Community

Teerasak Vichadee
Teerasak Vichadee

Posted on

How to read file and return as array of string or number as generic type

Actually we can write 2 functions: readFileAsArrayOfNumber and readFileAsArrayOfString, but I'm too lazy to do that.

Here the solution to read a file and convert it into array of generic type (string or number).

function readFile<T>(filePath: string): T[] {
  const contents = fs.readFileSync(filePath, 'utf-8')
  return contents.split(/\r?\n/).map(line => {
    const parsedNumber = parseInt(line, 10)
    if (!isNaN(parsedNumber)) {
      return parsedNumber as T
    }

    return line as T
  })
}
Enter fullscreen mode Exit fullscreen mode

Usage readFile<string>(filePath) or readFile<number>(filePath)

Latest comments (0)