通过打字稿声明全局类型是行不通的

时间:2021-01-18 02:33:59

标签: typescript

我尝试声明一个全局类型而不是每个文件导入。 vscode中没有语法错误,可以通过ctrl-click转到定义,但不起作用。我猜是ts-node的问题,因为tsc没有这个问题。

error message
TSError: ⨯ Unable to compile TypeScript:
src/index.ts(2,13): error TS2304: Cannot find name 'Mode'.
// src/index.ts
const mode: Mode = 'development'
console.log(mode);

// typings/index.d.ts
type Mode = 'production' | 'development'

// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "typings/*",
  ],
  "exclude": [
    "node_modules",
  ]
}

// package.json
  "scripts": {
    "dev": "npx ts-node ./src/index.ts"
  },

2 个答案:

答案 0 :(得分:0)

尝试使用 --files 选项

  "scripts": {
    "dev": "npx ts-node --files ./src/index.ts"
  },

ts-node 不会在启动时默认从 files 加载 includeexcludetsconfig.json

https://github.com/TypeStrong/ts-node#help-my-types-are-missing

答案 1 :(得分:0)

我只是更改了类型文件的路径,它起作用了。这让我很困惑。

typings/index.d.ts 之前 // typings/<module_name>/index.d.ts 之后

相关问题