-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Description
59 - Get Optional
If you solved yesterday's challenge (GetRequired) then this one should take all of 30 seconds to solve. There's a little bunch of 4 challenges here (starting with yesterday's) that are all related.
🎥 Video Explanation
🔢 Code
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
type A1 = GetOptional<{ foo: number; bar?: string }>;
type B1 = { bar?: string };
type C1 = Expect<Equal<A1, B1>>;
type A2 = GetOptional<{ foo: undefined; bar?: undefined }>;
type B2 = { bar?: undefined };
type C2 = Expect<Equal<A2, B2>>;
// ============= Your Code Here =============
type GetOptional<T> = {
[
P in keyof T as
T[P] extends Required<T>[P]
? never
: P
]: T[P];
};
// ============== Alternatives ==============
// @Jack-Works
type GetRequired<T> = {
[
P in keyof T as
T[P] extends Required<T>[P]
? P
: never
]: T[P];
};
type GetOptional<T> = Omit<T, keyof GetRequired<T>>
// sneak peak from @yi-tuan:
type GetOptional<T> = Pick<T, OptionalKeys<T>>;
// @dqn
type GetOptional<
T,
U extends Required<T> = Required<T>,
K extends keyof T = keyof T
> =
Pick<
T,
K extends keyof T
? T[K] extends U[K]
? never
: K
: never
>;➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
No labels