I want (for example) to forbid Date
instances when calling a function that accepts objects:
type ExcludeDate<T> = T extends Date ? never : T
function f<T extends object>(arg: T & ExcludeDate<T>) {
}
f(new Date()) // Error: Argument of type 'Date' is not assignable to parameter of type 'never'.(2345)
Is there any simpler way to achieve the same result?
I'm looking for something like this (which doesn't work of course):
function f<T extends Exclude<object, Date>>(arg: T) {
}
I want (for example) to forbid Date
instances when calling a function that accepts objects:
type ExcludeDate<T> = T extends Date ? never : T
function f<T extends object>(arg: T & ExcludeDate<T>) {
}
f(new Date()) // Error: Argument of type 'Date' is not assignable to parameter of type 'never'.(2345)
Is there any simpler way to achieve the same result?
I'm looking for something like this (which doesn't work of course):
function f<T extends Exclude<object, Date>>(arg: T) {
}
Share
Improve this question
edited Nov 28, 2024 at 9:48
jonrsharpe
122k30 gold badges268 silver badges476 bronze badges
asked Nov 28, 2024 at 9:46
Franck WolffFranck Wolff
966 bronze badges
3
|
1 Answer
Reset to default 1You can pass the generic param to a generic conditional type. To break the circular reference, use a mapped type:
Playground
type NotType<T extends object, U extends object, M = {[K in keyof T]: T[K]}> = M extends object ? M extends U ? never : M : never;
function f<T extends NotType<T, Date>>(arg: T) {
}
f(new RegExp('')) // ok
f(1); // not an object
f(new Date) // error
Date
is anobject
. A callf<object>(new Date())
will always succeed at the type level. – Bergi Commented Nov 28, 2024 at 12:59Date
s. Or you could approximate "not aDate
" like "anobject
without a definedgetFullYear
property" as shown in this playground link. It's not perfect since it will possibly exclude non-Date
s, but in practice things like this are good enough (who putsgetFullYear
in a random object?). Does that fully address the question? If so I'll write an answer or find a duplicate. If not, what's missing? – jcalz Commented Nov 28, 2024 at 23:55