gpt4 book ai didi

node.js - Typescript - tsc 编译器破坏了我的代码

转载 作者:搜寻专家 更新时间:2023-10-30 22:00:37 26 4
gpt4 key购买 nike

我用 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);就变成了redis_1.default.createClient(uri);`

尝试在 Node 中运行我的代码时出现以下错误

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 的类型有默认导出。确保您有最新的打字。如果您有最新的类型,import redis from 'redis'; 应该会引发编译时错误。

关于node.js - Typescript - tsc 编译器破坏了我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43485208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com