Common Errors

Below you find a list of common TypeScript errors along with the buggy code and the code which fixed the issue.

TS1055

error TS1055: Type ‘AxiosPromise‘ is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.

Buggy Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export const sendRequestWithCookie = async (
client: HttpClient,
config: AxiosRequestConfig,
engine: CRUDEngine
): AxiosPromise => {
const cookie: Cookie = await loadExistingCookie(engine);

if (!cookie.isExpired) {
config.headers = config.headers || {};
config.headers['Cookie'] = `zuid=${cookie.zuid}`;
config.withCredentials = true;
}

return client._sendRequest(config);
};

Fixed Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export const sendRequestWithCookie = (
client: HttpClient,
config: AxiosRequestConfig,
engine: CRUDEngine
): AxiosPromise => {
return loadExistingCookie(engine).then((cookie: Cookie) => {
if (!cookie.isExpired) {
config.headers = config.headers || {};
config.headers['Cookie'] = `zuid=${cookie.zuid}`;
config.withCredentials = true;
}

return client._sendRequest(config);
});
};

TS1066

error TS1066: In ambient enum declarations member initializer must be constant expression.

Buggy Code

1
2
3
4
5
enum PreKeyAuth {
INVALID = 'Invalid',
UNKNOWN = 'Unknown',
VALID = 'Valid'
}

Fixed Code

1
type PreKeyAuth = 'Invalid' | 'Unknown' | 'Valid';

TS1192

error TS1192: Module ‘.../logdown‘ has no default export.

Buggy Code

1
2
3
4
5
declare class Logdown {
// ...
}

export = Logdown;

Fixed Code

1
2
3
4
5
declare class Logdown {
// ...
}

export default Logdown;

TS1202

error TS1202: Import assignment cannot be used when targeting ECMAScript modules. Consider using ‘import * as ns from “mod”‘, ‘import {a} from “mod”‘, ‘import d from “mod”‘, or another module format instead.

Buggy Code

1
import sinon = require('sinon');

Fixed Code

1
import * as sinon from 'sinon';

TS1218

error TS1218: Export assignment is not supported when ‘–module’ flag is ‘system’.

Buggy Code

1
2
3
4
5
class LRUCache {
// ...
}

export = LRUCache;

Fixed Code

1
2
3
export class LRUCache {
// ...
}

TS2488

Type ‘{ [label: string]: string; }’ must have a ‘Symbol.iterator‘ method that returns an iterator.

Solution

You have to add a property called [Symbol.iterator] to your object. The value of this property has to return an iterator. Here you can learn how to create an iterator.

TS2304

error TS2304: Cannot find name ‘Promise’

Buggy Code

1
2
3
4
5
6
7
8
9
// ...

public load_prekey(prekey_id: number): Promise<Proteus.keys.PreKey> {
return new Promise((resolve) => {
resolve(42);
});
}

// ...

Fixed Code

Install es6-promise type definitions with the typings tool.

1
typings install dt~es6-promise --global --save

Adding the following line to the beginning of every file using definitions from es6-promise.

1
2
3
4
5
6
7
8
9
10
11
/// <reference path='es6-promise.d.ts' />

...

public load_prekey(prekey_id: number): Promise<Proteus.keys.PreKey> {
return new Promise((resolve) => {
resolve(42);
});
}

...

TS2304

error TS2304: Cannot find name ‘Promise’

Buggy Code

1
const UUID = require('uuidjs');

Fixed Code

1
npm install @types/node --save-dev

TS2305

error TS2305: Module ‘.../proteus‘ has no exported member ‘keys’.

Buggy Code

1
2
declare module keys {
}

Fixed Code

1
2
export module keys {
}

error TS2305: Module ‘.../proteus.keys‘ has no exported member ‘PreKey’.

Buggy Code

1
2
export module keys {
}

Fixed Code

1
2
3
4
export module keys {
class PreKey {
}
}

TS2306

error TS2306: File ‘../index.d.ts‘ is not a module.

TS2322

error TS2322: Type ‘Promise<{}>’ is not assignable to type ‘Promise

Buggy Code

1
2
3
4
remove(prekey_id: number): Promise<void> {
this.removed_prekeys.push(prekey_id);
return Promise.resolve();
}

Fixed Code

1
2
3
4
remove(prekey_id: number): Promise<void> {
this.removed_prekeys.push(prekey_id);
return Promise.resolve(undefined);
}

TS2339

error TS2339: Property ‘name‘ does not exist on type ‘Function‘.

Buggy Code

1
2
3
4
5
6
export class RecordNotFoundError extends Error {
constructor(public message: string) {
super(message);
this.name = this.constructor.name;
}
}

Fixed Code

1
2
3
4
5
6
export class RecordNotFoundError extends Error {
constructor(public message: string) {
super(message);
this.name = (<any>this).constructor.name;
}
}

TS2345

error TS2345: Argument of type ‘x‘ is not assignable to parameter of type ‘y‘.

1
2
3
4
5
6
error TS2345: Argument of type '(records: T[]) => void' is not assignable to parameter of type '(value: [{}, {}, {}, {}, > {}, {}, {}, {}, {}, {}]) => void | PromiseLike<void>'.
Types of parameters 'records' and 'value' are incompatible.
Type '[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]' is not assignable to type 'T[]'.
Types of property 'pop' are incompatible.
Type '() => {}' is not assignable to type '() => T'.
Type '{}' is not assignable to type 'T'.

Buggy Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
readAll<T>(tableName: string): Promise<T[]> {
return this.resolvePath(tableName).then(directory => {
return new Promise<T[]>((resolve, reject) => {
fs.readdir(directory, (error, files) => {
if (error) {
reject(error);
} else {
const recordNames = files.map(file => path.basename(file, path.extname(file)));
const promises = recordNames.map(primaryKey => this.read(tableName, primaryKey));
Promise.all(promises).then((records: T[]) => resolve(records));
}
});
});
});
}

Fixed Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
readAll<T>(tableName: string): Promise<T[]> {
return this.resolvePath(tableName).then(directory => {
return new Promise<T[]>((resolve, reject) => {
fs.readdir(directory, (error, files) => {
if (error) {
reject(error);
} else {
const recordNames = files.map(file => path.basename(file, path.extname(file)));
const promises: Array<Promise<T>> = recordNames.map(primaryKey => this.read(tableName, primaryKey));
Promise.all(promises).then((records: T[]) => resolve(records));
}
});
});
});
}

TS2349

error TS2349: Cannot invoke an expression whose type lacks a call signature. Type ‘Promise‘ has no compatible call signatures.

Buggy Code

1
2
3
function bugged(param: Promise<Object>): void {
param().then(() => console.log('error TS2349'));
}

Fixed Code

1
2
3
function bugged(param: Promise<Object>): void {
param.then(() => console.log('error TS2349'));
}

TS2351

error TS2351: This expression is not constructable. Type ‘EMA‘ has no construct signatures.

Buggy Code

RSI.ts
1
2
3
4
5
6
7
export class RSI {
private readonly avgGain: MovingAverage;

constructor(private readonly interval: number, Indicator: EMA) {
this.avgGain = new Indicator(this.interval);
}
}
EMA.ts
1
export class EMA {}

Fixed Code

RSI.ts
1
2
3
4
5
6
7
export class RSI {
private readonly avgGain: MovingAverage;

constructor(private readonly interval: number, Indicator: typeof EMA) {
this.avgGain = new Indicator(this.interval);
}
}

TS2497

error TS2497: Module ‘logdown‘ resolves to a non-module entity and cannot be imported using this construct.

Buggy Code

Export: logdown.d.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
declare class Logdown {
constructor(options?: Object);
public debug(...args: any[]): void;
public error(...args: any[]): void;
public info(...args: any[]): void;
public log(...args: any[]): void;
public warn(...args: any[]): void;
public static disable(...args: string[]): void;
public static enable(...args: string[]): void;
}

declare module "logdown" {
export = Logdown
}

Import: app.ts

1
import {Logdown} from "logdown";

Buggy Code #2

Export

1
2
3
4
5
6
7
8
9
10
11
12
13
14
declare module 'logdown' {
class Logdown {
constructor(options?: Object);
public debug(...args: any[]): void;
public error(...args: any[]): void;
public info(...args: any[]): void;
public log(...args: any[]): void;
public warn(...args: any[]): void;
public static disable(...args: string[]): void;
public static enable(...args: string[]): void;
}

export = Logdown;
}

Import

1
2
3
import {Logdown} from "logdown";
...
this.logger = new Logdown({prefix: 'abc', alignOuput: true});

Note: tsc option “allowSyntheticDefaultImports” must be set to true

Import

1
import Logdown = require('logdown');

TS2503

error TS2503: Cannot find namespace ‘Proteus’

Buggy Code

1
import Proteus from "wireapp-proteus";

Fixed Code

1
import {Proteus} from "wireapp-proteus";

TS2507

error TS2507: Type ‘typeof EventEmitter‘ is not a constructor function type.

Error happened when importing the exported class in another project.

Buggy Code

1
2
3
4
5
6
7
import EventEmitter from 'events';

export class WebSocketClient extends EventEmitter {
constructor() {
super();
}
}

Fixed Code

1
2
3
4
5
6
7
import {EventEmitter} from 'events';

export class WebSocketClient extends EventEmitter {
constructor() {
super();
}
}
Read more

TS2511

error TS2511: Cannot create an instance of an abstract class.

Buggy Code

1
2
3
myFunction = (strategyConstructor: typeof Strategy, config: StrategyConfig): Promise<Big> => {
// ....
}

Fixed Code

1
2
3
4
5
export interface Type<T> extends Function { new (...args: any[]): T; }

myFunction = (strategyConstructor: StrategyType<Strategy<StrategyConfig>>, config: StrategyConfig): Promise<Big> => {
// ....
}

Read more: Passing a class constructor as parameter to a function.

TS2532

error TS2532: Object is possibly ‘undefined’.

Buggy Code

1
2
3
if (queueObject) {
queueObject.retry -= 1;
}

Fixed Code

1
2
3
if (queueObject) {
queueObject.retry! -= 1;
}

Buggy Code

1
const ownerIds: string[] = process.env.WIRE_OWNER_IDS.split(',')

Fixed Code

1
const ownerIds: string[] = String(process.env.WIRE_OWNER_IDS).split(',')

TS2564

error TS2564: Property ‘key’ has no initializer and is not definitely assigned in the constructor.

Info: This error occurs with TypeScript 2.7 in “strict” mode because TypeScript 2.7 introduced a new flag called --strictPropertyInitialization, which tells the compiler to check that each instance property of a class gets initialized in the constructor body, or by a property initializer. See Strict Class Initialization.

Buggy Code

1
2
3
4
class CipherKey {
key: Uint8Array;
constructor() {}
}

Fixed Code

1
2
3
4
5
6
7
class CipherKey {
key: Uint8Array;

constructor() {
this.key = new Uint8Array([]);
}
}

TS2503

Cannot find name ‘process’. Do you need to install type definitions for node? Try npm i --save-dev @types/node.

Solution

Run yarn add --dev @types/node in your npm project.

TS2654

error TS2654: Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition.

Buggy Code

1
/// <reference path="../../../typings/index.d.ts" />

Fix

TS2656

error TS2656: Exported external package typings file ‘../proteus.d.ts‘ is not a module. Please contact the package author to update the package definition.

Buggy Code

1
2
declare module Proteus {
}

Fixed Code

1
2
export module Proteus {
}

TS2668

error TS2668: ‘export’ modifier cannot be applied to ambient modules and module augmentations since they are always visible.

Info

Ambient modules

To describe the shape of libraries not written in TypeScript, we need to declare the API that the library exposes. We call declarations that don’t define an implementation “ambient”. Typically, these are defined in .d.ts files. If you’re familiar with C/C++, you can think of these as .h files.

Source: https://www.typescriptlang.org/docs/handbook/modules.html

Module Augmentation

With module augmentation, users have the ability to extend existing modules such that consumers can specify if they want to import the whole module or just a subset.

Source: https://blogs.msdn.microsoft.com/typescript/2016/02/22/announcing-typescript-1-8-2/

Buggy Code

1
2
3
export module 'amplify' {
export function publish(topic: string, ...args: any[]): boolean;
}

Fixed Code

1
export function publish(topic: string, ...args: any[]): boolean;

Usage

1
import amplify = require("amplify");

TS2686

error TS2686: ‘ko’ refers to a UMD global, but the current file is a module. Consider adding an import instead.

Buggy Code

1
const downloadProgress = ko.observable();

Fixed Code

1
2
3
import ko from 'knockout';

const downloadProgress = ko.observable();

TS2686: ‘sinon’ refers to a UMD global, but the current file is a module. Consider adding an import instead.

Buggy Code

1
2
import { SinonFakeServer } from 'sinon';
let server: SinonFakeServer;

Fixed Code

1
2
import * as sinon from 'sinon';
let server: sinon.SinonFakeServer;

TS2693

error TS2693: ‘Candlestick‘ only refers to a type, but is being used as a value here.

Buggy Code

main.ts

1
2
import Candlestick from "../../chart/Candlestick"
const candle = new Candlestick();

Candlestick.ts

1
2
3
4
5
6
7
8
interface Candlestick {
close: number
high: number
low: number
open: number
}

export default Candlestick

Fixed Code

main.ts

1
2
import Candlestick from "../../chart/Candlestick"
const candle = new Candlestick();

Candlestick.ts

1
2
3
4
5
6
7
8
class Candlestick {
close: number = 0
high: number = 0
low: number = 0
open: number = 0
}

export default Candlestick

TS2794

error TS2794: Expected 1 arguments, but got 0. Did you forget to include ‘void’ in your type argument to ‘Promise’?

Solution

When a Promise resolves with nothing, then you need to define this return type (void) in recent versions of TypeScript.

Buggy Code

1
await new Promise((resolve, reject) => { resolve(); });

Fixed Code

1
await new Promise<void>((resolve, reject) => { resolve(); });

TS4020

error TS4020: ‘extends’ clause of exported class ‘StrategyPOJO‘ has or is using private name ‘Model‘.

Buggy Code

1
2
3
4
5
6
7
8
9
10
11
const {Model} = require('objection')

class StrategyPOJO extends Model {
static tableName = 'strategies'
config: string | undefined
exchange: string | undefined
identifier: string | undefined
symbol: string | undefined
}

export {StrategyPOJO}

Fixed Code

1
2
3
4
5
6
7
8
9
10
11
import {Model} from 'objection'

class StrategyPOJO extends Model {
static tableName = 'strategies'
config: string | undefined
exchange: string | undefined
identifier: string | undefined
symbol: string | undefined
}

export {StrategyPOJO}

TS4063

error TS4063: Parameter ‘config‘ of constructor from exported class has or is using private name ‘DoubleMovingAverageConfig‘.

Buggy Code

1
2
3
4
5
6
7
8
9
type DoubleMovingAverageConfig = {
lastBuyPrice: string,
lastSellPrice: string,
warmUpCandles: number,
}

class DoubleMovingAverage extends Strategy {
constructor(private setup: StrategySetup, private config?: DoubleMovingAverageConfig) {}
}

Fixed Code

1
2
3
4
5
6
7
8
9
export type DoubleMovingAverageConfig = {
lastBuyPrice: string,
lastSellPrice: string,
warmUpCandles: number,
}

class DoubleMovingAverage extends Strategy {
constructor(private setup: StrategySetup, private config?: DoubleMovingAverageConfig) {}
}

TS5055

error TS5055: Cannot write file ‘/Users/bennyn/projects/wireapp/wire-webapp-lru-cache/dist/commonjs/LRUCache.d.ts‘ because it would overwrite input file.

Buggy Code

tsconfig.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"compilerOptions": {
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": true,
"outDir": "dist/commonjs",
"removeComments": true,
"rootDir": "src/main/ts",
"sourceMap": false,
"target": "es5"
},
"exclude": [
"bower_components",
"node_modules",
"typings/browser",
"typings/browser.d.ts"
]
}

Fixed Code

tsconfig.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"compilerOptions": {
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": true,
"outDir": "dist/commonjs",
"removeComments": true,
"rootDir": "src/main/ts",
"sourceMap": false,
"target": "es5"
},
"exclude": [
"bower_components",
"dist/commonjs",
"node_modules",
"typings/browser",
"typings/browser.d.ts"
]
}

TS6053

error TS6053: File ‘/typings/index.d.ts‘ not found.

Buggy Code

1
/// <reference path='/typings/index.d.ts' />

Fixed Code

Use relative paths when using Triple-Slash Directives:

1
/// <reference path='../../../typings/index.d.ts' />

Read more: 8 Steps to Migrating from JavaScript to TypeScript

TS6059

error TS6059: File ‘/root/project/packages/server/package.json‘ is not under ‘rootDir’ ‘/root/project/packages/server/src‘. ‘rootDir’ is expected to contain all source files.

Buggy Code

1
import pkg from '../../../../package.json';

Fixed Code

1
const pkg = require('../../../../package.json');

TS6133

error TS6133: ‘volume‘ is declared but its value is never read.

Buggy Code

test.ts
1
const closes = ohlc.map(([time, open, high, low, close, volume]) => (close));
tsconfig.json
1
2
3
4
5
{
"compilerOptions": {
"noUnusedParameters": true
}
}

Fixed Code

tsconfig.json
1
2
3
4
5
{
"compilerOptions": {
"noUnusedParameters": false
}
}

error TS6133: ‘b‘ is declared but its value is never read.

test.ts
1
let b;
tsconfig.json
1
2
3
4
5
{
"compilerOptions": {
"noUnusedLocals": true
}
}

Fixed Code

tsconfig.json
1
2
3
4
5
{
"compilerOptions": {
"noUnusedLocals": false
}
}

TS7006

error TS7006: Parameter ‘person‘ implicitly has an ‘any’ type.

Buggy Code

test.ts

1
2
3
function greeter(person) {
return "Hello, " + person;
}

tsconfig.json

1
"noImplicitAny": true

Fixed Code

test.ts

1
2
3
function greeter(person: string) {
return "Hello, " + person;
}

TS7016

error TS7016: Could not find a declaration file for module ‘uuidjs‘.

Buggy Code

1
import UUID = require('uuidjs');

Fixed Code

1
const UUID = require('uuidjs');

Note: Proper fix would be to have a uuidjs.d.ts: https://github.com/LiosK/UUID.js/issues/6

TS7017

error TS7017: Element implicitly has an ‘any’ type because type ‘{}’ has no index signature.

Buggy Code

1
const recipients = {};

Fixed Code

1
const recipients: {[index: string]: number} = {};

Buggy Code

TypeScript compiler complains about this.db[tableName].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export default class IndexedDBEngine implements CRUDEngine {
public storeName: string;

constructor(private db: Dexie) {
this.storeName = db.name;
}

public create<T>(tableName: string, primaryKey: string, entity: T): Promise<string> {
if (entity) {
return this.db[tableName].add(entity, primaryKey).catch((error: Dexie.DexieError) => {
if (error instanceof Dexie.ConstraintError) {
const message: string = `Record "${primaryKey}" already exists in "${tableName}". You need to delete the record first if you want to overwrite it.`;
throw new RecordAlreadyExistsError(message);
} else {
throw error;
}
});
}
const message: string = `Record "${primaryKey}" cannot be saved in "${tableName}" because it's "undefined" or "null".`;
return Promise.reject(new RecordTypeError(message));
}
}

Fixed Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
export interface DexieInstance extends Dexie{
[index: string]: any;
}

export default class IndexedDBEngine implements CRUDEngine {
public storeName: string;

constructor(private db: DexieInstance) {
this.storeName = db.name;
}

public create<T>(tableName: string, primaryKey: string, entity: T): Promise<string> {
if (entity) {
return this.db[tableName].add(entity, primaryKey).catch((error: Dexie.DexieError) => {
if (error instanceof Dexie.ConstraintError) {
const message: string = `Record "${primaryKey}" already exists in "${tableName}". You need to delete the record first if you want to overwrite it.`;
throw new RecordAlreadyExistsError(message);
} else {
throw error;
}
});
}
const message: string = `Record "${primaryKey}" cannot be saved in "${tableName}" because it's "undefined" or "null".`;
return Promise.reject(new RecordTypeError(message));
}
}

TS7027

error TS7027: Unreachable code detected.

Buggy Code

1
2
process.exit(0);
console.log('Hello, World!');

Fixed Code

1
console.log('Hello, World!');