Using typescript, is there a way to constraint a generic type to allow values of type object only? Not array and other types.
For eg:
function check<O extends object>(ob: O): O {
return ob
}
check({}) // should be fine
check([]) // should show error, but does not.
A possible real world use case:
function extend<A extends object, B extends object>(a: A, b: B): A & B {
return {
...a,
...b,
};
}
// This is fine, return type is { x: number } & { y: string }
extend({x: 5}, {y: "str"})
// This should not be allowed
// Return type is number[] & string[]
// Accessing a property yields impossible types like number & string
extend([1,2,3], ["s", "i", "d"])
// More examples for variants which I don't want to allow
extend({}, function() {})
extend({}, new Map())
Assigning Generic ParametersBy passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.
Use extends keyword to constrain the type parameter to a specific type.
A type constraint on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.)
In TypeScript, the syntax for generics is rather simple. We use angle brackets to enclose the generic type-parameter.
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 !" : {})): O
function check<O extends object>(ob: O): O {
return ob
}
check({}) // should be fine
check([]) // error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With