检查 Typescript 中的 ReadonlyArray 中是否包含字符串

Dan*_*ung 6 typescript typeorm

背景是,我正在尝试读取.envDatabaseType构建 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[]

Ric*_*dad 1

注意 的类型process.env

export interface ProcessEnv {
    [key: string]: string | undefined
}
Run Code Online (Sandbox Code Playgroud)

您的问题是由 引起process.env.DB_CONNECTIONstring | undefined

所以当你这样做时:

SUPPORTED_DB_TYPES.indexOf(process.env.DB_CONNECTION)
Run Code Online (Sandbox Code Playgroud)

string您正在 的数组中搜索 a 'mysql' | 'mariadb' | 'postgres'

一个解决方案是输入DB_CONNECTIONas SUPPORTED_DB_TYPES[number],这会很糟糕,因为DB_CONNECTION可能是其他东西。否则你可以将其转换为any这不是一个坏主意。

在我看来,您的解决方案(使用 )as readonly string[]也不是一个坏主意。因为这个转换是有作用域的,并且由于该indexOf函数对您的使用过于严格而使用。

  • 是的,我知道,所以我正在寻找一种绕过选角的方法,因为选角并不完全好。 (3认同)