简体   繁体   English

在 typescript 中解构两个类型的数组时如何保留类型信息?

[英]How to keep type information when destructuring an array of two types in typescript?

How can I concatenate two arrays of different type A and B and keep it with separate typings as a result and not just我如何连接两个不同类型AB的 arrays 并因此将其与单独的类型保持在一起,而不仅仅是

Array<A | B>

and destructuring array back I want to keep types和解构数组我想保留类型

const [a1, a2] = concatenated;
const [,, b1, b2] = concatenated;

You can't do this with arbitrary length arrays. If they have fixed lengths, then you can handle it:您不能使用任意长度 arrays 执行此操作。如果它们具有固定长度,那么您可以处理它:

const a = [1,2] as [number, number];
const b = ['hello', 'bye'] as [string, string];

const c = [...a, ...b] as [number, number, string, string];
const [w, x, y, z] = c; // w and x are numbers, y and z are strings.

You can use extra function for this purpose:为此,您可以使用额外的 function:

type Value = string | number

const concat = <
    A extends Value,
    ATuple extends A[],
    B extends Value,
    BTuple extends B[]
>(a: [...ATuple], b: [...BTuple]): [...ATuple, ...BTuple] => [...a, ...b]


// [1, 2, "hello", "bye"]
const result = concat([1, 2], ['hello', 'bye'])

const [a /** 1 */, b, c /** "hello" */, d] = result

Playground 操场

Thanks to function argument inference, every element of the tuple is properly infered感谢 function 参数推断,元组的每个元素都被正确推断

More information avout inference on function arguments you can find in my blog有关 function arguments 的更多信息,您可以在我的博客中找到

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

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