Home > Back-end >  Typescript assigns wrong types to variables (using fs modules)
Typescript assigns wrong types to variables (using fs modules)

Time:03-09

fs.promises.readFile(filePath, {encoding: "utf8")) returns any while it should return string.

If I hover over readFile it shows me this:enter image description here

ts file:

const fs = require('fs');
const path = require('path');

async function doSomething():Promise<Array<string>> {
    const fileText = await fs.promises.readFile(path.join(__dirname, "testFile"), {encoding: "utf8"});
    const rows = fileText.split(/\n|\r\n|\r/);
    const splitRows = rows.map(value => value.split('\t'));
    return splitRows;
}

testFile contents:

columnA1    columnB1
columnA2    columnB2

The compiler should throw an error because doSomething returns Promise<Array<Array<string>>> and not Promise<Array<string>>.

If I change the first line in the function to:

const fileText:string = await fs.promises.readFile(path.join(__dirname, "testFile"), {encoding: "utf8"});

The compiler behaves as it should be.

I do not understand why it doesn't recognize fileText as a string.

And even if fileText isn't a string it should know that split returns an array right?

CodePudding user response:

By using require, you're importing fs and path untyped. (If you hover over either of them it should show any.) If you use the import syntax, the compiler will behave as you expect:

import * as fs from 'fs';
import * as path from 'path';

async function doSomething():Promise<Array<string>> {
    const fileText = await fs.promises.readFile(path.join('__dirname', "testFile"), {encoding: "utf8"});
    const rows = fileText.split(/\n|\r\n|\r/);
    const splitRows = rows.map(value => value.split('\t'));
    return splitRows;
}

TypeScript playground

  • Related