打字稿:对于相同类型,省略等于空

时间:2020-05-21 20:11:06

标签: typescript generics

我在尝试实现行为如下的通用类型时遇到了困难:

  1. 如果目标类型比源类型宽,那么结果类型将包含源中未显示的目标类型的所有属性

  2. 如果目标类型与源具有相同的属性,则结果应为空(仅允许空对象)。

上面的第一个条件似乎很容易实现,例如:

// S - stands for Source type
// T - stands for Target type that could be wider
type DiffType<S, T> = Omit<T, keyof S>;

但不满足第二个条件,假设:

type A = { a: string; }
type A1 = { a: string; }
type AB = { a: string; b: string; }

// works as expected
const x: DiffType<AB, A> = {
    b: 'b'
}

// unfortunately it doesn't throw error
const x1: DiffType<A, A1> = {
    foo: 'bar'
}

// but should allow only (the desired behavior)
const x2: DiffType<A, A1> = {}

我尝试做类似的事情,但这也无济于事:

type DiffType<S, T> = {} extends Omit<T, keyof S> ? {} : Omit<T, keyof S>;

有人可以建议如何实施这种行为吗?我希望有可能:)

1 个答案:

答案 0 :(得分:0)

最后!不幸的是,只有找到答案,这似乎才很容易! :(

type DiffType<S, T> = {} extends Omit<T, keyof S>
    ? { [K: string]: never }
    : Omit<T, keyof S>;

有必要通过[K: string]: never拒绝在对象中手动添加任何键。不要小看“从不”的力量!