【问题标题】:How to stop TypeScript from merging object types如何阻止 TypeScript 合并对象类型
【发布时间】:2022-06-11 03:20:21
【问题描述】:

在下面的例子中:

type TA = { a: 1 }
type TB = { b: 2 }

const testa: TA = {
  a: 1
}

const testb: TB = {
  b: 2
}

我只想允许类型为 TA 或类型为 TB 的对象,而不是组合对象。 TypeScript 中允许以下内容:

const testEitherOr: TA | TB = {
  a: 1,
  b: 2 // This seems like it should not be allowed
}

如何确保test 仅匹配两种对象类型之一?

【问题讨论】:

标签: typescript


【解决方案1】:

正如上面的 cmets 所推荐的,都指向这个解决方案

type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never }
type XOR<T, U> = T | U extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U

这不适用于联合或多种类型。

但这很好用:Why does A | B allow a combination of both, and how can I prevent it?

type AllKeys<T> = T extends unknown ? keyof T : never;
type Id<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;
type _ExclusifyUnion<T, K extends PropertyKey> =
    T extends unknown ? Id<T & Partial<Record<Exclude<K, keyof T>, never>>> : never;
type ExclusifyUnion<T> = _ExclusifyUnion<T, AllKeys<T>>;

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 2020-05-03
    • 1970-01-01
    • 2022-07-20
    • 2021-10-24
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    相关资源
    最近更新 更多