arabidopsis / typescript-definitions

Apache License 2.0
71 stars 20 forks source link

How to add typescript decorators? #6

Closed mocsy closed 9 months ago

mocsy commented 4 years ago

Consider the following code:

use serde::{Deserialize, Serialize};
use validator::Validate;

#[derive(Debug, Serialize, Deserialize, Clone, Validate)]
pub struct Post {
    #[validate(length(min = 10, max = 20))]
    title: String,
    #[validate(range(min = 0, max = 10))]
    rating: u32,
    #[validate(email)]
    email: String,
    #[validate(url)]
    post_url: String,
}

This is the corresponding typescript definition, currently written by hand:

import {validate, validateOrReject, IsPositive, IsInt, Length, IsEmail, IsURL, Min, Max} from "class-validator";

export class Post {
    @Length(10, 20)
    title: string;

    @IsPositive()
    @IsInt()
    @Min(0)
    @Max(10)
    rating: number;

    @IsEmail()
    email: string;

    @IsURL()
    post_url: Date;
}

Is it possible to add typescript decorators manually?

Would it be possible to add a feature to generate these decorators as well, from the #[validate] attribute?

https://www.typescriptlang.org/docs/handbook/decorators.html https://github.com/typestack/class-validator https://github.com/Keats/validator