logo
down
shadow

Modifying Property Values in Typescript Decorator


Modifying Property Values in Typescript Decorator

Content Index :

Modifying Property Values in Typescript Decorator
Tag : typescript , By : lamberms
Date : January 12 2021, 01:40 AM

Hope this helps I have class level variable in an Angular Service. I need to prepend some value to the variables value via decorators. How can I achieve?
import "reflect-metadata";

const enum MicroService {
  NAME = "microserviceName/"
}

function Service(prefix: string): PropertyDecorator {
  return (target, key): void => {
    let original = target[key];
    Reflect.deleteProperty(target, key);
    Reflect.defineProperty(target, key, {
      get: () => original,
      set: newVal => {
        original = `${prefix}${newVal}`;
      },
      enumerable: true,
      configurable: true
    });
  };
}

export class MyClass {
  @Service(MicroService.NAME)
  public foo: string = "hello";

  public exec(): string {
    return this.foo;
  }
}

const c = new MyClass();

console.log(c.foo); // - prints: microserviceName/hello

c.foo = "test";

console.log(c.foo); // - prints: microserviceName/test

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

vue.js how to bind a property to a method return value when using TypeScript and vue-property-decorator?


Tag : javascript , By : WuJanJai
Date : March 29 2020, 07:55 AM
Hope this helps When decorated with Emit, the return Vue of the method is used to determine if the event should be emitted or not.
In other words, methods decorated with Emit will always return undefined.
getPlayerAmount(itemName: string): string {
    this.$emit('get-player-amount', itemName);
    if (this.inventory[itemName]) {
        return `'${this.inventory[itemName].amount}'`;
    } else {
        return '0';
    }
}

getIcon(itemName: string): string {
    const icon = Items.getItemData(itemName).icon;
    if (icon) this.$emit('get-icon', itemName);
    return icon;
}

Vue&TypeScript: 'el' property for vue-property-decorator/vue-class-component?


Tag : typescript , By : D B
Date : March 29 2020, 07:55 AM
I hope this helps you . vue-property-decorator is intended to augment Vue components with class-style syntax in TypeScript. The code in question does not fit the criteria because it's not a component. Let's assume you meant to convert the script in this single-file-component:
App.vue:
<script>
export default {
  data() {
    return {
      message: 'Hello Vue!'
    }
  }
}
</script>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class App extends Vue {
  message = 'Hello Vue!'
}
</script>
<!-- index.html -->
<body>
  <div id="app"></div>

  <script>
    new Vue({
      el: '#app'
    });
  </script>
</body>

How to get value of another property via decorator in TypeScript


Tag : typescript , By : yossi
Date : March 29 2020, 07:55 AM
seems to work fine target will not be an instance of the class, it will be the class itself. to access field values you will need to use this inside the get/set function and not use arrow functions:
export class UmsDictionary {
    public aField = "SUPER";
    @PropertyAlias('aField')
    public dictionary = "dictionary";
}

export function PropertyAlias(name: string) {
    return (target: any, key: string) => {
        Object.defineProperty(target, key, {
            configurable: false,
            get: function (this: { [name: string]: any}) {
                return this[name];
            },
                set: function (this: { [name: string]: any}) {
            }
        })
    }
}
const dct = new UmsDictionary();
console.log("VALUE = " + dct.dictionary); //undefined

Typescript cannot access property type from typescript decorator. (Target is: {})


Tag : typescript , By : mansoor
Date : March 29 2020, 07:55 AM
it should still fix some issue So, after a few days of messing around I FINALLY found an answer as to why this wasn't working and it hurts me as to how blindingly obvious it was. So in the TS config file there is a flag that needs to be set to true in order for decorator meta data to be emitted. The flag is shown below:
"emitDecoratorMetadata": true

TypeScript complains about existing Vue component property defined with vue-property-decorator


Tag : javascript , By : user107021
Date : March 29 2020, 07:55 AM
it fixes the issue I recommend you to use this library: https://github.com/kaorun343/vue-property-decorator
With this you can declare your prop inside your component class.
import { Vue, Component, Prop } from 'vue-property-decorator'

@Component
class TestProp extends Vue {
  @Prop(String) myId: string!
}
Related Posts Related QUESTIONS :
  • Why does my outDir contain a (largely duplicate) src dir?
  • Storybook in Create React App withTypeScript still compiles when component has illegal types
  • Typescript: make one of two properties optional
  • Typescript Types: Type of object value which can be used as index signature
  • How do I combine "Omit" and "Pick"?
  • How to get generic type from a method signature return type
  • In TypeScript, define a type for any object that has required properties
  • Typescript - Array of extended Classes of specific Parent
  • Typing for a getValues + map operation
  • How to get predefined property from sub-object?
  • How to wait stack to complete before executing code in AWS CDK?
  • Typescript: What is the difference between an optional and a not optional class member with default value
  • TypeScript type modification when using defaults and object destructuring assignment
  • How to Update json object value in array from another array of same json object structure in Typescript
  • How do I specify the correct return type for mapStateToProps?
  • TypeScript's import() typeof json
  • how to convert a string value to enum in typescript
  • Can I extract optional properties from a type in Typescript?
  • UnionTypes: PartialRequired and PickRequired
  • Disable ESLint for TypeScript files
  • How to initiate "findInFiles" with VSCode extension API?
  • How to keep ES6 syntax when transpiling with Typescript
  • How to transform interface children's type to type[]?
  • How to transform input data with NestJS and TypeORM
  • How to use defaultNavigationOptions's properties with TypeScript?
  • Unable to create a managed promise instance - if function written with async/await
  • TypeScript generics error: Property does not exist on type
  • How to solve implicit any type to index type error in typescript?
  • Unexpected let, use const instead
  • Variable 'x' is used before being assigned
  • Access Typescript object property based on template argument
  • Why did Typescript allow me to create an object without specifying required fields?
  • How to format an array of dates using datepipe in angular?
  • Resolve 'Conflicting definitions for node' TS4090 error in VS 2017
  • Is it possible to have a function accept class instances, but not accept plain objects?
  • Extending a union type exactly
  • TypeScript function generic can only work for function overload with more than one signatures
  • Cannot find module that is defined in tsconfig `paths`
  • Why won't TS let me index into a compatible object type?
  • Can one represent indexable signatures in io-ts
  • Typescript allow extension of AxiosConfig
  • How to match nested Keys in Typescript
  • Enforce explicit function return type annotations?
  • winston custom transport with typescript
  • Switching based on object type
  • Typescript gives different errors in vscode than through webpack
  • How to run TypeScript from local directory instead of global
  • Why is typescript upset about comparing to undefined?
  • Nested queries in Apollo Server
  • TypeScript dynamically derived fields from another type
  • How can I create a generic type for a dynamic generated object created from an array
  • Typing declaration disambiguate Object or Function
  • Fix "Continue without scanning the task output" in Visual Studio Code
  • could be instantiated with a different subtype of constraint 'object'
  • Type guard with complement in false branch
  • Manually widen type
  • How do I type for arrays with ordered types of unknown length?
  • Typescript switch case confusing compiler
  • Using externally defined component with Vue and TypeScript class decorator syntax
  • typescript multiple generic cannot infered properly
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com