Skip to content

Commit 7a6ed56

Browse files
committed
Modify FromSchema so that optional properties are actually optional
1 parent 91fbc51 commit 7a6ed56

2 files changed

Lines changed: 13 additions & 10 deletions

File tree

src/json/index.ts

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,7 @@ export type Validator<T> = {
4747
};
4848

4949
/** Extracts `T` from `Validator<T>`. */
50-
export type UnwrapValidator<V> =
51-
V extends Validator<infer A>
52-
? V["required"] extends true
53-
? A
54-
: A | undefined
55-
: never;
50+
export type UnwrapValidator<V> = V extends Validator<infer A> ? A : never;
5651

5752
/** A validator for string fields in schemas. */
5853
export const string = {
@@ -73,10 +68,20 @@ export function optional<T>(validator: Validator<T>) {
7368
/** Represents an arbitrary object schema. */
7469
export type Schema = Record<string, Validator<any>>;
7570

71+
/** Extracts the required keys from `S`. */
72+
export type RequiredKeys<S extends Schema> = {
73+
[K in keyof S]: S[K]["required"] extends true ? K : never;
74+
}[keyof S];
75+
76+
/** Extracts optional keys from `S`. */
77+
export type OptionalKeys<S extends Schema> = {
78+
[K in keyof S]: S[K]["required"] extends true ? never : K;
79+
}[keyof S];
80+
7681
/** Constructs an object type corresponding to a schema. */
7782
export type FromSchema<S extends Schema> = {
78-
[K in keyof S]: UnwrapValidator<S[K]>;
79-
};
83+
[K in RequiredKeys<S>]: UnwrapValidator<S[K]>;
84+
} & { [K in OptionalKeys<S>]?: UnwrapValidator<S[K]> };
8085

8186
/**
8287
* Validates that `obj` satisfies at least `schema`. Additional keys are accepted.

src/start-proxy/types.test.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,6 @@ test("credentialToStr - hides passwords", (t) => {
145145
const secret = "password123";
146146
const credential = {
147147
type: "maven_credential",
148-
username: null,
149148
password: secret,
150149
url: "https://localhost",
151150
} satisfies types.Credential;
@@ -160,7 +159,6 @@ test("credentialToStr - hides tokens", (t) => {
160159
const secret = "password123";
161160
const credential = {
162161
type: "maven_credential",
163-
username: null,
164162
token: secret,
165163
url: "https://localhost",
166164
} satisfies types.Credential;

0 commit comments

Comments
 (0)