Skip to content

Commit

Permalink
feat: implement 'nullable' and multiple types for union
Browse files Browse the repository at this point in the history
  • Loading branch information
lbguilherme committed Dec 21, 2020
1 parent 2794b80 commit 2085e84
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
21 changes: 17 additions & 4 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ declare namespace AsTypedInternal {
interface SchemaBase {
$id?: string;
$ref?: string;
type?: string;
type?: string | string[];
title?: string;
description?: string;
nullable?: boolean;
default?: any;
examples?: any[];
}
Expand Down Expand Up @@ -211,9 +212,11 @@ declare namespace AsTypedInternal {
| (ValueType extends StringSchema ? never : string)
| (ValueType extends BoolSchema ? never : boolean);

type ResolveRecursiveInternal<
SchemaType
> = SchemaType extends SchemaDeclaration<null>
type ResolveRecursiveInternal<SchemaType> = SchemaType extends {
nullable: true;
}
? ResolveRecursiveInternal<Omit<SchemaType, "nullable">> | null
: SchemaType extends SchemaDeclaration<null>
? null
: SchemaType extends ConstSchema<infer Value>
? Value
Expand All @@ -237,6 +240,16 @@ declare namespace AsTypedInternal {
>
: SchemaType extends ArraySchema<infer ValueType>
? ResolveArray<ValueType>
: SchemaType extends {
type: [infer Type];
}
? ResolveRecursiveInternal<Omit<SchemaType, "type"> & { type: Type }>
: SchemaType extends {
type: [infer Type, ...infer Rest];
}
?
| ResolveRecursiveInternal<Omit<SchemaType, "type"> & { type: Type }>
| ResolveRecursiveInternal<Omit<SchemaType, "type"> & { type: Rest }>
: never;

// TODO
Expand Down
19 changes: 19 additions & 0 deletions test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ assert(_ as AsTyped<{ type: "integer" }>, _ as number);

assert(_ as AsTyped<{ type: "string" }>, _ as string);

assert(_ as AsTyped<{ type: ["string", "null"] }>, _ as string | null);

assert(_ as AsTyped<{ type: "string"; nullable: true }>, _ as string | null);

assert(_ as AsTyped<{ type: "string"; nullable: false }>, _ as string);

assert(_ as AsTyped<{ type: "boolean" }>, _ as boolean);

assert(_ as AsTyped<{ type: "null" }>, _ as null);
Expand Down Expand Up @@ -182,6 +188,19 @@ assert(
_ as { arr?: Array<{ [name: string]: string }> }
);

assert(
_ as AsTyped<{
type: ["object", "boolean", "null"];
properties: {
arr: {
type: "array";
items: { type: "object"; additionalProperties: { type: "string" } };
};
};
}>,
_ as { arr?: Array<{ [name: string]: string }> } | boolean | null
);

/*
* assert(
* _ as AsTyped<{
Expand Down

0 comments on commit 2085e84

Please sign in to comment.