我们知道我们无法在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));
如果在includes
的compilerOptions.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)[]
有很多方法可以做到这一点(减法):