我试图在1D或2D类型记录数组中修改一组字符串,如下所示:
// this part of the code is from a library, I cannot modify it.
let x: string[] | string[][];
document.write(Math.random().toString());
if (Math.random() > 0.5) {
x = ["one", "two", "three"];
} else {
x = [["one", "two", "three"], ["four", "five", "six"], ["seven", "eight", "nine"]];
}
// the code below needs to modify the output from the library
if (Array.isArray(x) && x.every(item => typeof item === "string")) {
x = x.map(item => "prefix-" + item);
} else {
x = x.map(item_array => item_array.map(item => "prefix-" + item));
}
document.write(x.toString());我一直从类型记录编译器中得到这个错误:
Cannot invoke an expression whose type lacks a call signature. Type '(<U>(callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[]) | (<U>(callbackfn: (value: string[], index: number, array: string[][]) => U, thisArg?: any) => U[])' has no compatible call signatures.有什么方法可以让类型记录编译器在每个带大括号的部分实现正确的类型?
编辑:我在上面的代码中添加了注释,以指出我不能编辑执行分配任务的代码。
发布于 2019-05-06 13:32:13
编译器不明白,那么,当您检查x时,您会发现它是否是string[]。让编译器知道这一点的支持方法是将检查打包到用户定义类型保护功能中,如下所示:
// note that the return type of this is "x is string[]"
function isStringArray(x: any): x is string[] {
return Array.isArray(x) && x.every(item => typeof item === "string");
}
if (isStringArray(x)) {
x = x.map(item => "prefix-" + item); // okay
} else {
x = x.map(item_array => item_array.map(item => "prefix-" + item)); // okay
}这在运行时或多或少是一样的(通过额外的函数调用),但现在编译器将if isStringArray(x) {...x...} else {...x...}解释为对x类型的检查。在“然后”子句(其中isStringArray(x)是true)中,x将从string[] | string[][]缩小到string[]。在“where”子句(其中isStringArray(x)是false)中,x将从string[] string[] | string[][]中删除string[],将其缩小到string[][]。然后,这两个子句中的代码按预期进行编译。
希望这会有所帮助;祝你好运!
发布于 2019-05-06 07:39:52
编译失败,因为当我们将x类型声明为string[]或string时。当x的定义发生时,x的类型被赋值&根据分配给x的值固定。
要使编译成功=>
if (Math.random() > 0.5) {
x = ["one", "two", "three"];
x = x.map(item => "prefix-" + item);
} else {
x = [["one", "two", "three"], ["four", "five", "six"], ["seven", "eight", "nine"]];
x = x.map(item_array => item_array.map(item => "prefix-" + item));
}https://stackoverflow.com/questions/55999807
复制相似问题