我正在使用一个名为EnvObj的库来帮助我在用Typescript编写的Node项目中设置环境变量。我的env.ts文件看起来像这样:
import env = require('envobj')
export interface Env {
"PORT": number,
"PG_CONNECTION" : string,
"REDIS_CONNECTION": string,
"SERVER_HOST": string,
"SERVER_SECURE": boolean,
"COOKIE_KEY": string,
"GOOGLE_API_CLIENT_ID": string,
"GOOGLE_API_CLIENT_SECRET": string,
"GOOGLE_API_DOMAIN": string,
"CLEARBIT_API_KEY": string
}
export default env <Env>({
"PORT": 3000,
"PG_CONNECTION": String,
"REDIS_CONNECTION": String,
"SERVER_HOST": 'localhost:3000',
"SERVER_SECURE": false,
"COOKIE_KEY": String,
"GOOGLE_API_CLIENT_ID": String,
"GOOGLE_API_CLIENT_SECRET": String,
"GOOGLE_API_DOMAIN": '',
"CLEARBIT_API_KEY": String
})
运行代码时,出现以下错误:
src/support/env.ts:16:20 - error TS2344: Type 'Env' does not satisfy the constraint 'ValidResult'. Index signature is missing in type 'Env'.
如果我深入研究envobj,则ValidResult接口如下所示:
interface ValidResult {
[key: string]: string | number | boolean
}
似乎与所写的Env接口兼容。
向Env对象添加索引签名会给我这个错误:
src/support/env.ts:17:26 - error TS2345: Argument of type '{ "PORT": number; "PG_CONNECTION": StringConstructor; "REDIS_CONNECTION": StringConstructor; "SER...' is not assignable to parameter of type 'Config<Env>'.
Property '"PORT"' is incompatible with index signature.
Type 'number' is not assignable to type 'never'.
17 export default env <Env>({
~
18 "PORT": 3000,
~~~~~~~~~~~~~~~
...
27 "CLEARBIT_API_KEY": String
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
28 })
~
知道我要去哪里哪里吗?
答案 0 :(得分:0)
听起来很奇怪,如果您将Env
指定为type
而不是interface
,错误就会消失。
import env = require('envobj')
export type Env = {
"PORT": number,
"PG_CONNECTION" : string,
"REDIS_CONNECTION": string,
"SERVER_HOST": string,
"SERVER_SECURE": boolean,
"COOKIE_KEY": string,
"GOOGLE_API_CLIENT_ID": string,
"GOOGLE_API_CLIENT_SECRET": string,
"GOOGLE_API_DOMAIN": string,
"CLEARBIT_API_KEY": string
}
// No more error!
export default env <Env>({
"PORT": 3000,
"PG_CONNECTION": String,
"REDIS_CONNECTION": String,
"SERVER_HOST": 'localhost:3000',
"SERVER_SECURE": false,
"COOKIE_KEY": String,
"GOOGLE_API_CLIENT_ID": String,
"GOOGLE_API_CLIENT_SECRET": String,
"GOOGLE_API_DOMAIN": '',
"CLEARBIT_API_KEY": String
})