Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何在TypeScript中检查对象是否为只读数组?_Arrays_Typescript_Typechecking - Fatal编程技术网

Arrays 如何在TypeScript中检查对象是否为只读数组?

Arrays 如何在TypeScript中检查对象是否为只读数组?,arrays,typescript,typechecking,Arrays,Typescript,Typechecking,如何使用只读数组(ReadonlyArray)执行数组检查(如array.isArray()) 例如: type ReadonlyArray test=ReadonlyArray | string |未定义; 让ReadOnlyRayTest:ReadOnlyRayTest; if(readonlyraytest&!Array.isArray(readonlyraytest)){ //在这里,我希望'readonlyraytest'是一个字符串 //但是TypeScript编译器认为它如下所示:

如何使用只读数组(
ReadonlyArray
)执行数组检查(如
array.isArray()

例如:

type ReadonlyArray test=ReadonlyArray | string |未定义;
让ReadOnlyRayTest:ReadOnlyRayTest;
if(readonlyraytest&!Array.isArray(readonlyraytest)){
//在这里,我希望'readonlyraytest'是一个字符串
//但是TypeScript编译器认为它如下所示:
//让ReadOnlyArray测试:字符串|只读字符串[]
}
使用常规数组,TypeScript编译器正确识别它必须是if条件内的字符串。

TypeScript中的相关问题

建议的解决方法是将重载添加到
isArray
的声明中:

declare global {
    interface ArrayConstructor {
        isArray(arg: ReadonlyArray<any> | any): arg is ReadonlyArray<any>
    }
}
声明全局{
接口阵列构造器{
isArray(arg:ReadonlyArray | any):arg是ReadonlyArray
}
}
应该是这样的

interface ArrayConstructor {
  isArray(arg: unknown): arg is unknown[] | readonly unknown[];
}
并在typescript中进行测试

const a = ['a', 'b', 'c'];
if (Array.isArray(a)) {
  console.log(a); // a is string[]
} else {
  console.log(a); // a is never
}

const b: readonly string[] = ['1', '2', '3']

if (Array.isArray(b)) {
  console.log(b); // b is readonly string[]
} else {
  console.log(b); // b is never
}

function c(val: string | string[]) {
  if (Array.isArray(val)) {
    console.log(val); // val is string[]
  }
  else {
    console.log(val); // val is string
  }
}

function d(val: string | readonly string[]) {
  if (Array.isArray(val)) {
    console.log(val); // val is readonly string[]
  }
  else {
    console.log(val); // val is string
  }
}

function e(val: string | string[] | readonly string[]) {
  if (Array.isArray(val)) {
    console.log(val); // val is string[] | readonly string[]
  }
  else {
    console.log(val); // val is string
  }
}

谢谢,但是我应该把接口声明放在哪里呢?如果我只是将它粘贴到出现问题的文件中,它将不起作用。@mamiu在模块中,您需要将其包装在“全局声明”中。看,太棒了!在Github问题上发布了此答案。