Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - tsc compiler breaks my code

I wrote this code in Typescript

import redis from 'redis';
import Promise from 'bluebird';

const DEFAULT_REDIS_TTL = 7200; // 2 hours

export default class Redis {

    readonly client : any;
    ttl : number = DEFAULT_REDIS_TTL;

    constructor(uri? : string, ttl : number = DEFAULT_REDIS_TTL) {
        this.client = redis.createClient(uri);
    }

    ...
}

export { Redis };

the compiler gives me this

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var redis_1 = require("redis");
var bluebird_1 = require("bluebird");
var DEFAULT_REDIS_TTL = 7200; // 2 hours
var Redis = (function () {
    function Redis(uri, ttl) {
        if (ttl === void 0) { ttl = DEFAULT_REDIS_TTL; }
        this.ttl = DEFAULT_REDIS_TTL;
        this.client = redis_1.default.createClient(uri);
        this.client.on('error', function (error) {
            console.error(error);
        });
...
exports.Redis = Redis;
exports.default = Redis

I don't know why 'redis.createClient(uri);just becomeredis_1.default.createClient(uri);`

I get the following error when trying to run my code in node

build/Lib/Cache/Redis.js:11
        this.client = redis_1.default.createClient(uri);
                                     ^

TypeError: Cannot read property 'createClient' of undefined

my tsconfig looks like this

{
    "compilerOptions": {
        "module": "mymodule",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false,
         "module": "commonjs",
        "outDir": "build"
    },

    "include": [
        "src/**/*.ts"
    ],

    "exclude": [
        "node_modules"
    ]
}

I run the compiler in main directory

tsc

I'm using node 6.7.2

like image 766
user7887107 Avatar asked Feb 04 '26 16:02

user7887107


1 Answers

Change your import to:

import * as redis from 'redis';

I don't think the typings for redis has a default export. Make sure you have the latest typings. If you have the latest typings, import redis from 'redis'; should throw a compile time error.

like image 140
Saravana Avatar answered Feb 07 '26 05:02

Saravana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!