Conversation
| public exec(): string { | ||
| return (this.a + this.b).toString(); | ||
| } | ||
| } |
There was a problem hiding this comment.
это не реализация паттерна декоратор
https://refactoring.guru/ru/design-patterns/decorator/typescript/example
| let exampleInstance = new Example(); | ||
| exampleInstance.email = "fkkldfjg"; // генерирует эксепшен | ||
| exampleInstance.email = "misha@mail.ru"; // выводит в консоль e-mail valid | ||
| exampleInstance.email = "misha@mail.ru"; // выводит в консоль e-mail valid No newline at end of file |
| constructor(){ | ||
| this.m = "hello"; | ||
| } | ||
| } |
| if (!(prop in val)) | ||
| throw new Error(); | ||
| } | ||
| } |
There was a problem hiding this comment.
Нужно ещё сделать return descriptor , иначе он не будет работать. Метод set не будет вызываться
| return function(target: Object, propertyKey: string | symbol) : any{ | ||
| let descriptor: PropertyDescriptor = { | ||
| set: function(val: any){ | ||
| if (typeof val === typeof type) |
There was a problem hiding this comment.
val = объект
type = функция
значит это выражение будет всегда false
| class Example1 { | ||
| @validate(ValueExample1, "id") | ||
| public propValueExample1: any; | ||
|
|
There was a problem hiding this comment.
правильное решение ниже
function validate<T, P extends keyof T>(type: new () => T, prop: P): (target: Object, propertyKey: string | symbol) => any {
let temp: T;
return (target: Object, propertyKey: string | symbol): PropertyDescriptor => {
let descriptor: PropertyDescriptor = {
get: function () {
return temp;
},
set: function (val: T) {
if (!(val instanceof type)) {
throw new Error("Устанавливается значение которое не соотвтетсвует типу");
}
if (temp[prop]) {
throw new Error("У требуемого поля не верный примитивный тип");
}
console.log("value valid");
temp = val;
}
};
return descriptor;
};
}
class ValueExample1 {
public value: string;
public id: number;
}
class ValueExample2 {
public prop3: undefined;
public prop2: boolean;
}
class Example {
@Validate(ValueExample1, "id1")
public propValueExample1: any;
@validate(ValueExample2, "prop3")
public propValueExample2: any;
}
let ex1 = new Example();
let objValExample = new ValueExample1();
objValExample.id = 1;
objValExample.value = "qwe";
ex1.propValueExample1 = objValExample;
ex1.propValueExample2 = false;
|
Итого 6 балов |
No description provided.