-
Notifications
You must be signed in to change notification settings - Fork 0
/
02759-medium-requiredbykeys.ts
42 lines (35 loc) · 1.04 KB
/
02759-medium-requiredbykeys.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// ============= Test Cases =============
import type { Equal, Expect } from "./test-utils";
interface User {
name?: string;
age?: number;
address?: string;
}
interface UserRequiredName {
name: string;
age?: number;
address?: string;
}
interface UserRequiredNameAndAge {
name: string;
age: number;
address?: string;
}
type cases = [
Expect<Equal<RequiredByKeys<User, "name">, UserRequiredName>>,
Expect<Equal<RequiredByKeys<User, "name" | "age">, UserRequiredNameAndAge>>,
Expect<Equal<RequiredByKeys<User>, Required<User>>>,
// @ts-expect-error
Expect<Equal<RequiredByKeys<User, "name" | "unknown">, UserRequiredName>>
];
// ============= Your Code Here =============
type MapKeys<T> = { [Key in keyof T]: T[Key] };
type RequiredByKeys<
T,
K extends keyof T | never = never,
RequiredFields = Required<Pick<T, K>>
> = [K] extends [never]
? Required<T>
: MapKeys<RequiredFields & Omit<T, keyof RequiredFields>>;
type test1 = RequiredByKeys<User, "name">;
const Test1: test1 = { name: "asd", address: "asd", age: 123 };