Typescript – tsc编译器会中断我的代码
我在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 };
编译器给了我这个
"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
我不知道为什么'redis.createClient(uri); just become
redis_1.default.createClient(uri);`
尝试在节点中运行我的代码时出现以下错误
build/Lib/Cache/Redis.js:11 this.client = redis_1.default.createClient(uri); ^ TypeError: Cannot read property 'createClient' of undefined
我的tsconfig
看起来像这样
{ "compilerOptions": { "module": "mymodule", "target": "es5", "noImplicitAny": false, "sourceMap": false, "module": "commonjs", "outDir": "build" }, "include": [ "src/**/*.ts" ], "exclude": [ "node_modules" ] }
我在主目录下运行编译器
tsc
我正在使用node 6.7.2
将您的导入更改为:
import * as redis from 'redis';
我不认为redis的types具有默认导出。 确保你有最新的打字。 如果您有最新的types,请import redis from 'redis';
应该抛出一个编译时错误。