Dan*_*ung 6 typescript typeorm
背景是,我正在尝试读取.env
以DatabaseType
构建 TypeORM 连接,如下所示:
const config: ConnectionOptions = {
type: process.env.DB_CONNECTION, // A type of DatabaseType = 'mysql'|'postgres'|'sqlite'|...
//...
}
Run Code Online (Sandbox Code Playgroud)
然后上面我有支持的列表DatabaseType
:
const SUPPORTED_DB_TYPES = ['mysql', 'mariadb', 'postgres'] as const; // This array contains selected DatabaseType
Run Code Online (Sandbox Code Playgroud)
当我想缩小类型范围时,问题就出现了。这个函数目前可以工作,但是涉及到转换:
const isSupportedDBType = (dbConnection: string|undefined): dbConnection is typeof SUPPORTED_DB_TYPES[number] =>
dbConnection !== undefined &&
((SUPPORTED_DB_TYPES as readonly string[]).indexOf(dbConnection) > -1);
if(!isSupported(process.env.DB_CONNECTION)) {/*...*/}
Run Code Online (Sandbox Code Playgroud)
如果删除,我必须强制转换,因为出现以下错误as readonly string[]
:
“string”的参数类型不能分配给“mysql”|“mariadb”|“postgres”的参数类型
有没有办法使用 来做到这一点as readonly string[]
?
注意 的类型process.env
:
export interface ProcessEnv {
[key: string]: string | undefined
}
Run Code Online (Sandbox Code Playgroud)
您的问题是由 引起process.env.DB_CONNECTION
的string | undefined
。
所以当你这样做时:
SUPPORTED_DB_TYPES.indexOf(process.env.DB_CONNECTION)
Run Code Online (Sandbox Code Playgroud)
string
您正在 的数组中搜索 a 'mysql' | 'mariadb' | 'postgres'
。
一个解决方案是输入DB_CONNECTION
as SUPPORTED_DB_TYPES[number]
,这会很糟糕,因为DB_CONNECTION
可能是其他东西。否则你可以将其转换为any
这不是一个坏主意。
在我看来,您的解决方案(使用 )as readonly string[]
也不是一个坏主意。因为这个转换是有作用域的,并且由于该indexOf
函数对您的使用过于严格而使用。
归档时间: |
|
查看次数: |
1040 次 |
最近记录: |