如何检查类型是否为数组



答案:您不能

从这里我知道,要检查一个值是否是一个列表,你可以使用Array.isArray((,但我有一个奇怪的情况,我有查询函数

export async function query<T = unknown>(sql: string, options?: unknown): Promise<T> {
const pool = await initializePool()
const result = await pool.query(sql, options);
return /* T is of type list */ ? result : [result];
}

我不能在类型上使用Array.isArray((,我想知道是否有某种类型的函数可以在t.上使用

问题是,pool.query总是返回一个数组,如果可能的话,我想立即销毁它

const initializePool = async () => {
if (pool) {
return pool;
}
const CREDS = { connectionLimit: 500000, ...MYSQL_CREDS, multipleStatements: true }
pool = await mysql.createPool(CREDS)
return pool
}

TypeScript被转换为JavaScript,JS中没有保留任何TypeScript语法(除了枚举等罕见的东西(。您不能让运行的JavaScript根据TypeScript可以推断出的类型来更改其行为。您还需要将逻辑放入JavaScript中。

所以,你需要这样的东西:

export async function query(sql: string, options?: unknown) {
const pool = await initializePool()
const result = await pool.query(sql, options);
return Array.isArray(result) ? result : [result];
}

理论上,让pool.query检查传递的字符串(如果是泛型的(并推断结果是否是数组是可能的(请参见ts-sql(,但看起来mysql并没有实现这样的功能——因此,您无法缩小传递的查询是否会导致result成为数组的范围。(这里并不是说你需要它,因为返回类型看起来并不依赖于它。(

最新更新