Is there a way to constraint a generic type to plain objects only in typescript?
You can use a conditional type to add to the parameter of the parameter if O
extends any[]
. What you add can ensure that the call will be an error. I usually add string literal types and think of them as a custom error message:
function check<O extends object>(ob: O & (O extends any[] ? "NO Arrays !" : {})): Ofunction check<O extends object>(ob: O): O { return ob}check({}) // should be finecheck([]) // error
In newer versions of Typescript, you can use object & Exclude<T, any[]>
to represent an object that cannot be an array.