You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Issue
Currently there is no way to enforce type-safety on property decorators.
Current property decorator syntax
functiondefaultValue<T>(value: T){// No way to enforce that target[propertyKey] is of type Treturnfunction(target: any,propertyKey: string){Object.defineProperty(target,propertyKey,{value: value});};}classFoo{
@defaultValue(4)x: number;// Compiles without error
@defaultValue('foo')y: number;// Also compiles without error, no current way to enforce type safety}
Proposed property decorator syntax
functiondefaultValue<T>(value: T){returnfunction(target: any,propertyKey: string,descriptor: TypedPropertyDescriptor<T>){// Note that descriptor has the value (<TypedPropertyDescriptor<T>>undefined)Object.defineProperty(target,propertyKey,{value: value});};}classFoo{
@defaultValue(4)x: number;// Compiles without error
@defaultValue('foo')y: number;// Error: argument of type 'TypedPropertyDescriptor<number>' is not// assignable to parameter of type 'TypedPropertyDescriptor<string>'}
The descriptor parameter could really be anything; its only purpose is to provide the compiler with type information about the property being decorated. I used TypedPropertyDescriptor<T> here for consistency with method and accessor decorators. Current downlevel (ES5) emit already passes undefined explicitly as the third parameter to the decorator function.
The text was updated successfully, but these errors were encountered:
PyroVortex
changed the title
Provide type information to property decorators
Suggestion: Provide type information to property decorators
Oct 26, 2016
Property decorators do not get PropertyDiscriptor's like method decorators do. that would be the way to pass the type to the function.
The reason this does not happen is that these properties are not defined until the constructor runs, so the value can not be computed ahead of time as it is an expression and can have side effects.
It is possible that we can do this when Public class fields TC39 proposal is ratified. this will give us some standard framework to represent initialization of a property that will run at construction time.
Issue
Currently there is no way to enforce type-safety on property decorators.
Current property decorator syntax
Proposed property decorator syntax
The
descriptor
parameter could really be anything; its only purpose is to provide the compiler with type information about the property being decorated. I usedTypedPropertyDescriptor<T>
here for consistency with method and accessor decorators. Current downlevel (ES5) emit already passesundefined
explicitly as the third parameter to the decorator function.The text was updated successfully, but these errors were encountered: