首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对类型记录数组中的不同维数执行不同的代码(使用nap)?

如何对类型记录数组中的不同维数执行不同的代码(使用nap)?
EN

Stack Overflow用户
提问于 2019-05-06 06:26:05
回答 2查看 27关注 0票数 0

我试图在1D或2D类型记录数组中修改一组字符串,如下所示:

代码语言:javascript
复制
// 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());

我一直从类型记录编译器中得到这个错误:

代码语言:javascript
复制
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.

有什么方法可以让类型记录编译器在每个带大括号的部分实现正确的类型?

编辑:我在上面的代码中添加了注释,以指出我不能编辑执行分配任务的代码。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-06 13:32:13

编译器不明白,那么,当您检查x时,您会发现它是否是string[]。让编译器知道这一点的支持方法是将检查打包到用户定义类型保护功能中,如下所示:

代码语言:javascript
复制
// 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[][]。然后,这两个子句中的代码按预期进行编译。

希望这会有所帮助;祝你好运!

票数 0
EN

Stack Overflow用户

发布于 2019-05-06 07:39:52

编译失败,因为当我们将x类型声明为string[]或string时。当x的定义发生时,x的类型被赋值&根据分配给x的值固定。

要使编译成功=>

代码语言:javascript
复制
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));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55999807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档