从部分类型中排除空对象

时间:2019-09-05 03:37:34

标签: typescript

使用Partial<SomeType>时,从技术上讲,空对象满足该类型检查。有办法排除这种情况吗?

    interface MyType {
        foo: string
        bar: string
    }

    function someFunction(obj: Partial<MyType>) {
        // whatever
    }

    someFunction({}) // ideally, I would like this should throw a type error

2 个答案:

答案 0 :(得分:1)

this answer的启发(这也详细解释了它的工作原理),这是您需要的:

type AtLeastOne<T, U = {[K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U];

然后使用此新类型代替Partial

Playground

答案 1 :(得分:0)

如果您的类型很简单,则一种方法是定义所有有效的情况。如果是复杂类型,则可能无法维护。

type MyType = { foo: string } | { bar: string } | { foo: string; bar: string; }

function someFunction(obj: MyType) {}

someFunction({ foo: "baz" }); // valid
someFunction({ bar: "baz" }); // valid
someFunction({ foo: "baz", bar: "baz" }); // valid
someFunction({}); // error

TypeScript playground

此答案中共享了另一个解决方案:https://stackoverflow.com/a/49725198/2690790

type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
  T,
  Exclude<keyof T, Keys>
> &
  {
    [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>
  }[Keys];

interface MyType {
  foo: string;
  bar: string;
}

function someFunction(obj: RequireAtLeastOne<MyType>) {}

someFunction({ foo: "baz" }); // valid
someFunction({ bar: "baz" }); // valid
someFunction({ foo: "baz", bar: "baz" }); // valid
someFunction({}); // error

TypeScript playground