Force object to have at least one key ( Object.keys(o).length > 0 )

Viewed 528

Say I have this object

export interface Name {
   [key: string]: boolean
}

const v = <Name>{};

how do I prevent this from compiling? What I want to do is force v to have at least one property:

const v = <Name>{foo: true};
1 Answers

You can't do this for a variable. To begin with you can't at the same time infer the type of a variable and add an annotation to it. And by default any annotation you add can't constrain the existence of at least one arbitrary property.

If you have a function, and you want to ensure a function parameter has at least one property, we can use a conditional type to generate something akin to a custom error:

function noEmpty<T>(o: T & (keyof T extends never ? "No empty object" : {})) {

}

noEmpty({}) // err Argument of type '{}' is not assignable to parameter of type '{} & "No empty object"'.
noEmpty({ a: ""})
Related