Modify FromSchema so that optional properties are actually optional

This commit is contained in:
Michael B. Gale
2026-04-30 11:54:21 +01:00
parent 91fbc51606
commit 7a6ed56219
2 changed files with 13 additions and 10 deletions
+13 -8
View File
@@ -47,12 +47,7 @@ export type Validator<T> = {
};
/** Extracts `T` from `Validator<T>`. */
export type UnwrapValidator<V> =
V extends Validator<infer A>
? V["required"] extends true
? A
: A | undefined
: never;
export type UnwrapValidator<V> = V extends Validator<infer A> ? A : never;
/** A validator for string fields in schemas. */
export const string = {
@@ -73,10 +68,20 @@ export function optional<T>(validator: Validator<T>) {
/** Represents an arbitrary object schema. */
export type Schema = Record<string, Validator<any>>;
/** Extracts the required keys from `S`. */
export type RequiredKeys<S extends Schema> = {
[K in keyof S]: S[K]["required"] extends true ? K : never;
}[keyof S];
/** Extracts optional keys from `S`. */
export type OptionalKeys<S extends Schema> = {
[K in keyof S]: S[K]["required"] extends true ? never : K;
}[keyof S];
/** Constructs an object type corresponding to a schema. */
export type FromSchema<S extends Schema> = {
[K in keyof S]: UnwrapValidator<S[K]>;
};
[K in RequiredKeys<S>]: UnwrapValidator<S[K]>;
} & { [K in OptionalKeys<S>]?: UnwrapValidator<S[K]> };
/**
* Validates that `obj` satisfies at least `schema`. Additional keys are accepted.
-2
View File
@@ -145,7 +145,6 @@ test("credentialToStr - hides passwords", (t) => {
const secret = "password123";
const credential = {
type: "maven_credential",
username: null,
password: secret,
url: "https://localhost",
} satisfies types.Credential;
@@ -160,7 +159,6 @@ test("credentialToStr - hides tokens", (t) => {
const secret = "password123";
const credential = {
type: "maven_credential",
username: null,
token: secret,
url: "https://localhost",
} satisfies types.Credential;