如何检查对象是否为TypeScript中的只读数组? [英] How to check if an object is a readonly array in TypeScript?
本文介绍了如何检查对象是否为TypeScript中的只读数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用只读数组(ReadonlyArray
)进行数组检查(如Array.isArray()
)?
How to do an array check (like Array.isArray()
) with a readonly array (ReadonlyArray
)?
例如:
type ReadonlyArrayTest = ReadonlyArray<string> | string | undefined;
let readonlyArrayTest: ReadonlyArrayTest;
if (readonlyArrayTest && !Array.isArray(readonlyArrayTest)) {
// Here I expect `readonlyArrayTest` to be a string
// but the TypeScript compiler thinks it's following:
// let readonlyArrayTest: string | readonly string[]
}
使用通常的数组,TypeScript编译器可以正确识别它必须是if条件内的字符串.
With an usual array the TypeScript compiler correctly recognises that it must be a string inside the if condition.
推荐答案
与之相关打字稿中出现问题.
@jcalz 提出的建议解决方法正在为isArray
的声明添加重载:
Suggested workaround by @jcalz is adding overload to declaration of isArray
:
declare global {
interface ArrayConstructor {
isArray(arg: ReadonlyArray<any> | any): arg is ReadonlyArray<any>
}
}
这篇关于如何检查对象是否为TypeScript中的只读数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文