如何在打字稿中减去两个只读数组

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

我们知道我们无法在Typescript中连接只读数组,但是我们可以做到这一点

readonly ArrA = [1, 2, 3] as const;
readonly ArrB = [4, 5] as const;
readonly Arr = [...ArrA, ...ArrB];

所以加法完成了,减法怎么样?ps:如果不是只读的,我们可以这样做

ArrA.filter(n => !ArrB.includes(n));
javascript typescript readonly
2个回答
1
投票

如果在includescompilerOptions.lib中添加“ ES7”,则[tsconfig.json将可用(与只读无关)。>


如果您关心数组成员级别的类型安全,则可以执行以下操作:

const ArrA = [1, 2, 3] as const;
const ArrB = [3, 4, 5] as const;

// Aliases for tuple-member types
type ArrAMember = typeof ArrA[number] // (1 | 2 | 3)
type ArrBMember = typeof ArrB[number] // (3 | 4 | 5)

type ExclusionListMember = Exclude<ArrAMember, ArrBMember> // (1 | 2)

// Type-guard to verify exclusion
function isExcludedByB(i: ArrAMember): i is ExclusionListMember {
    return !ArrB.includes(i as any)
}

const ArrC = ArrA.filter(isExcludedByB)
//    ^ (1 | 2)[]

0
投票

有很多方法可以做到这一点(减法):

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