extendable schema type#183
Open
newash wants to merge 2 commits intotdegrunt:masterfrom
newash:patch-1
Open
Conversation
With the existing type definition it was not possible to add extra fields to the schema (such as "default"). Using generics now anything can be added.
Collaborator
|
@newash Could you provide a quick code example of how this would be used, and maybe how it runs for you with and without the patch? Thanks! |
Author
|
@awwright Sure, this is my code for generating defaults: export interface MySchema extends Schema<MySchema> {
default: any;
}
const validator = new Validator<MySchema>();
function addDefaults(instance: any, schema: MySchema): any {
if (schema.default !== undefined && instance === undefined) {
return schema.default;
}
return instance;
}
function validate(instance: any, uri: string, extension: RewriteFunction<MySchema>): ValidatorResult<MySchema> {
return validator.validate(instance, uri, { rewrite: extension });
}
export function createDefaults(instance: any, uri: string): any {
let result: ValidatorResult<MySchema> = validate(instance, uri, addDefaults);
if (!result.valid)
throw "something went wrong with model creation";
return result.instance;
}Without the generics, the I know it's not a small change and I'd be the happiest if you knew a neater solution, but I'm afraid this is the neat one. |
this is a non-typesafe solution but less obstructive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
With the existing type definition it was not possible to add extra fields to the schema (such as "default").
Using generics now anything can be added.
With my current project it's kinda necessary, so it would be nice of you if you could pull it in. Thanks!