输入相同类型元素的数组,除了最后一个元素

问题描述 投票:0回答:1

我有一个服务器响应,它是 IFoo 元素的数组,但最后一个是 IBar 类型。

我想删除最后一个元素并将其分配给一个新变量。我应该怎么做?

我尝试将响应键入为元组,但 TypeScript 并没有像我期望的那样拆分元素的类型。

const response = [...IFoo[], IBar];
const lastElement = response.pop()

// typeof response returns [...IFoo[], IBar]
// typeof lastElement returns IFoo | IBar | undefined

//expected result:
// typeof response returns IFoo[]
// typeof lastElement returns IBar
typescript tuples typescript-typings
1个回答
0
投票

我怀疑你被类型断言困住了。您有正确的回复类型:

type ResponseTuple = [...IFoo[], IBar];

由于您可能坚持使用类型断言,让我们至少将它们包装在一个可重用、可测试的函数中,该函数生成一个更易于使用的结构:

// A function to split the response into something easier to work with
function splitResponse(response: ResponseTuple): {bar: IBar, foos: IFoo[]} {
    if (response.length < 1) {
        // No bar at all => error (you could make another decision, but this is an example)
        throw new Error(`Can't split an empty response`);
    }
    // Grab the bar non-destructively, using a type assertion :-(
    const bar = response[response.length - 1] as IBar;
    // Grab the foos non-destructively, using a type assertion :-(
    const foos = response.slice(0, -1) as IFoo[];
    // Return the more useful format
    return {bar, foos};
}

使用它:

const { bar, foos } = splitResponse(someResponse);

游乐场示例

© www.soinside.com 2019 - 2024. All rights reserved.