Using ConditionalKeys
with a condition type of Date
fails to match an object property with type Date | undefined
. The danger with this is that the type has to be an exact match of Base
's union and there's no feedback to a developer when something breaks.
For example when the Base type changes, the condition type needs to change to match, but there's no errors when nothing matches.
It would be nice to have a new type that will match if the condition is in the base union rather than an exact match.
In the below example we made a date
property optional when it wasn't originally, but we missed the fact that a function that uses ConditionalKeys was no longer identifying the properties anymore because the types no longer matched exactly.
import { type ConditionalKeys } from 'type-fest'
interface Data {
date?: Date
}
const data: Data = {
date: new Date()
}
type DateKeys = ConditionalKeys<Data, Date> // fails to find key
Maybe something like this: TS Playground
export type ConditionalKeysExtract<Base, Condition> = NonNullable<
// Wrap in `NonNullable` to strip away the `undefined` type from the produced union.
{
// Map through all the keys of the given base type.
[Key in keyof Base]:
// Pick only keys where condition is in the base type
Extract<Base[Key], Condition> extends never
// Discard this key since the condition fails.
? never
// Retain this key since the condition passes.
: Key;
// Convert the produced object into a union type of the keys which passed the conditional test.
}[keyof Base]
>;
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too