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 }) }
Usage readFile<string>(filePath)
or readFile<number>(filePath)
Top comments (0)