Borislav Hadzhiev
Wed Mar 16 2022·2 min read
Photo by Ian Dooley
The TypeScript error "String literal expected" occurs when we have a syntax
error, most often in an import statement. To solve the error, make sure to not
use any variables when resolving your import paths and import as
import {myFunction} from './myFile'
.
Here are 3 examples of how the error occurs.
// 1. ⛔️ Error: String literal expected.ts(1141) import {sum} = require('./another-file') // 2. ⛔️ Error: String literal expected.ts(1141) const pathToModule = './another-file'; import { myFunction } from `${pathToModule}`; // 3. ⛔️ Error: String literal expected.ts(1141) import {sum}, Employee from './another-file'
All of the examples above have syntactical errors.
The error in the first example is that we are mixing the ES Modules and CommonJS syntax.
Instead, you should import named exports as:
// 👇️ named import import { sum } from './another-file'; console.log(sum(50, 50)); // 👉️ 100
This assumes that you have a named export in a file called another-file
that's
located in the same directory.
// 👇️ named export export function sum(a: number, b: number) { return a + b; }
The import path depends on where the module is located and if you're importing a local file or a 3rd party library.
For example if another-file
was located one directory up, you would import as
import {sum} from '../another-file'
.
If you have a default export, omit the curly braces when importing it.
Here is an a file called another-file
, which has a named and a default export.
// 👇️ named export export function sum(a: number, b: number) { return a + b; } // 👇️ default export export default class Employee {}
When you import them, always import the default export first.
// 👇️ default and named import import Employee, { sum } from './another-file'; console.log(sum(50, 50)); // 👉️ 100 console.log(Employee);
In my experience, most real world codebases exclusively use named exports and imports, because they make it easier to leverage your IDE for autocompletion and auto-imports.
You also don't have to think about which members are exported with a default or named export.