Typescript assigns wrong types to variables (using fs modules)

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

If I hover over readFile it shows me this:Typescript assigns wrong types to variables (using fs modules)

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|rn|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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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|rn|r/);
    const splitRows = rows.map(value => value.split('t'));
    return splitRows;
}

TypeScript playground


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x