从 Partial 类型中排除空对象

Jos*_*eph 0 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
Run Code Online (Sandbox Code Playgroud)

luk*_*ter 9

受到这个答案的极大启发(它还详细解释了它的工作原理),这就是您需要的:

type AtLeastOne<T, U = {[K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U];
Run Code Online (Sandbox Code Playgroud)

然后使用这个新类型代替Partial.

操场