错误TS2403:后续变量声明必须具有相同的类型

时间:2016-07-05 17:54:40

标签: typescript

错误

我收到此打字稿错误:

  

错误TS2403:后续变量声明必须具有相同的类型。变量环境'必须是' string'类型,但这里有类型' any'。

代码

的package.json

...
"typescript": "^1.8.10",
...

server.ts

var environment = require('./config/config.js')()

./配置/ config.ts

module.exports = function(): string {
  //Environment
  let env:string = process.env.NODE_ENV || 'development'
  return env
}

问题:

我需要做什么才能将函数的返回值识别为string

修改

tsconfig

{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

安装节点

我添加了typings.json

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160621231320"
  }
}

我记得使用tsd install。我有一个名为typings的文件夹,在该文件夹中是另一个名为nodeindex.d.ts的文件夹。我认为这与node.d.ts相同?

编辑2

gulp for frontend(angularjs)和backend(nodejs)

const gulp = require('gulp');
const gutil = require('gulp-util');
const paths = gulp.paths;
var $ = require('gulp-load-plugins')();

const tscConfig = require('../tsconfig.json');

gulp.task('scripts-frontend', function () {
  gulp.src(paths.src + '/systemjs.config.js')
   .pipe(gulp.dest(paths.out + '/'));

  return gulp.src([paths.src + '/frontend/**/*.ts', paths.typings + '/**/*', '!' + paths.src + '/**/*.spec.ts'])
    .pipe($.sourcemaps.init())
    .pipe($.typescript(tscConfig.compilerOptions))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest(paths.out + '/frontend/'));
});

gulp.task('scripts-backend', function () {
  return gulp.src([paths.src + '/backend/**/*.ts', paths.typings + '/**/*', paths.src + '/server.ts', '!' + paths.src + '/**/*.spec.ts'])
    .pipe($.sourcemaps.init())
    .pipe($.typescript(tscConfig.compilerOptions))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest(paths.out + '/backend/'));
});

1 个答案:

答案 0 :(得分:1)

我发现您的文件扩展名为.ts(例如config.ts)。不要在ts文件中使用var/require!引入其他ts文件尤其如此。

var environment = require('./config/config.js')()应该是:

import config = require('./config/config.js'); 
const environment = config();

module.exports = function(): string {应该是:

export = function(): string {

更多

https://basarat.gitbooks.io/typescript/content/docs/project/external-modules.html