DEV Community

Lumin
Lumin

Posted on

2 2

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)

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more