import fs from "fs" ; interface IFileReader { isJSONFile ( filePath ) : boolean ; readTextFile ( filePath ) : string ; readJSONFile ( filePath ) : unknown ; } const scanFiles = ( dirPath , reader ) => fs . readdirSync ( dirPath ) . reduce < Record < string , unknown > > ( ( a , fileName ) => { if ( reader . isJSONFile ( fileName ) ) { a [ fileName ] = reader . readJSONFile ( `${ dirPath }/${ fileName }` ) ; } else { a [ fileName ] = reader . readTextFile ( `${ dirPath }/${ fileName }` ) ; } return a ; } , { } ) ; const fileReader = { isJSONFile : ( filePath ) : boolean => filePath . endsWith ( ".json" ) , readTextFile : ( filePath ) : string => fs . readFileSync ( filePath , "utf8" ) . toString ( ) , readJSONFile : ( filePath ) : unknown => JSON . parse ( fs . readFileSync ( filePath , "utf8" ) . toString ( ) ) , } ; console . log ( scanFiles ( "./data" , fileReader ) ) ;