我们知道我们无法在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)[]
关于javascript - 如何在Typescript中减去两个只读数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59206806/