【发布时间】:2018-07-31 08:33:35
【问题描述】:
这是错误的精简 sn-p:
export default function formatSql(this: EscapeFunctions, sqlQuery: string, values: QueryParams) {
if (isPlainObject(values)) {
console.log(values[p]); // <-- Element implicitly has an 'any' type because type 'QueryParams' has no index signature.
} else if (Array.isArray(values)) {
// ...
} else {
throw new Error(`Unsupported values type`);
}
// ...
}
QueryParams 定义为:
export type QueryParams = StringMap | any[];
export interface StringMap {
[_:string]: any,
}
所以,如果我没记错的话,StringMap 有一个“索引签名”,isPlainObject 定义为:
export function isPlainObject(obj: any): obj is object {
return isObject(obj) && (
obj.constructor === Object // obj = {}
|| obj.constructor === undefined // obj = Object.create(null)
);
}
所以我认为isPlainObject 检查会排除any[] 类型,因此values 应该必然被推断为StringMap,但这似乎不是正在发生的事情。
即使我让isPlainObject 返回obj is StringMap,Typescript 仍然会抱怨。
怎么会?有什么方法可以在不强制转换所有内容的情况下完成这项工作?
【问题讨论】: