简体   繁体   English

TypeScript中的数组元素类型断言问题

[英]Array element type assertion problem in TypeScript

type Plan<T> = [T[], ...T[]];

I declared a type named Plan , which includes a repetitive plan in index 0 and in the rest what to execute initially.我声明了一个名为Plan的类型,其中包括索引0中的重复计划以及最初执行的内容。

example) const life: Plan<string> = [ ["getUp", "work", "sleep"], "birth", "grow" ]例如) const life: Plan<string> = [ ["getUp", "work", "sleep"], "birth", "grow" ]

And I tried to define the following function:我试图定义以下函数:

function parsePlan<T>(plan: Plan<T>, index: number): T {
    if(index < 1) throw Error();

    return index < plan.length
    ?plan[index]
    :plan[0][(index-plan.length)%(plan[0].length)]
}

but It says there is a problem that this would return T | T[]但它说有一个问题,这将返回T | T[] T | T[] . T | T[]

If index < 1 it will throw Error() and that makes it impossible to return T[] .如果index < 1 ,它将throw Error()并且无法返回T[]

Why does this error appear, and how can I fix this error?为什么会出现此错误,我该如何解决此错误?

Thanks a lot for your help.非常感谢你的帮助。

Type narrowing doesn't work in all cases, as you expect.如您所料,类型缩小并非在所有情况下都有效。

It does work on a single variable though, when you add type guards or type predicates to narrow down.但是,当您添加类型保护或类型谓词以缩小范围时,它确实适用于单个变量。

This will work:这将起作用:

type Plan<T> = [T[], ...T[]];

function parsePlan<T>(plan: Plan<T>, index: number): T {
    const item = plan[index]

    if (Array.isArray(item)) throw Error();

    return index < plan.length ? item : plan[0][(index-plan.length)%(plan[0].length)]
}

Also playground here . 这里也是游乐场。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM