-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Description
2852 - OmitByType
Similar to PickByType (a previous challenge) this is a bit of an expansion pack on the Omit challenge (and, builtin). It's a good exercise that will challenge your memory of how to implement Omit.
🎥 Video Explanation
🔢 Code
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
interface Model {
name: string
count: number
isReadonly: boolean
isEnable: boolean
}
type A1 = OmitByType<Model, boolean>;
type B1 = {
name: string;
count: number
};
type C1 = Expect<Equal<A1, B1>>;
type A2 = OmitByType<Model, string>;
type B2 = {
count: number;
isReadonly: boolean;
isEnable: boolean
};
type C2 = Expect<Equal<A2, B2>>;
type A3 = OmitByType<Model, number>;
type B3 = {
name: string;
isReadonly: boolean;
isEnable: boolean
};
type C3 = Expect<Equal<A3, B3>>;
// ============= Your Code Here =============
type PickByType<T, U> = {
[P in keyof T as
T[P] extends U
? P
: never
]: T[P];
}
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
type Exclude<T, U> =
T extends U
? never
: T;
type Omit<T, K extends PropertyKey> =
Pick<
T,
Exclude<keyof T, K>
>;
type OmitByType<T, K> = {
[P in keyof T as T[P] extends K ? never : P]: T[P]
}
// ============== Alternatives ==============
// credit to @z-juln
type KeyByType<T extends object, K> =
keyof T extends `${infer P}` // grab specific keys
? P extends keyof T
? T[P] extends K
? P
: never
: never
: never;
type OmitByType<T extends object, K> = {
[P in Exclude<keyof T, KeyByType<T, K>>]: T[P]
};➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
No labels