Fix - String literal expected error in TypeScript Import

avatar

Borislav Hadzhiev

Wed Mar 16 20222 min read

banner

Photo by Ian Dooley

Fix - String literal expected error in TypeScript Import #

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.

index.ts
// 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:

index.ts
// 👇️ 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.

another-file.ts
// 👇️ 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'.

Make sure you aren't using any variables when resolving the path of your imports - it's not allowed. The path should be statically resolved.

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.

another-file.ts
// 👇️ 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.

index.ts
// 👇️ default and named import import Employee, { sum } from './another-file'; console.log(sum(50, 50)); // 👉️ 100 console.log(Employee);
The main difference between named and default exports and imports is - you can have multiple named exports per file, but you can only have a single default export.

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.