Marcelo Kapi

1589397720

A practical guide to TypeScript decorators

We can all agree that JavaScript is an amazing programming language that allows you to build apps on almost any platform. Although it comes with its own fair share of drawbacks, TypeScript has done a great job of covering up some gaps inherent in JavaScript. Not only does it add type safety to a dynamic language, but it also comes with some cool features that don’t exist yet in JavaScript, such as decorators.

#Uncategorized #javascript #typescript

What is GEEK

Buddha Community

A practical guide to TypeScript decorators

Marcelo Kapi

1589397720

A practical guide to TypeScript decorators

We can all agree that JavaScript is an amazing programming language that allows you to build apps on almost any platform. Although it comes with its own fair share of drawbacks, TypeScript has done a great job of covering up some gaps inherent in JavaScript. Not only does it add type safety to a dynamic language, but it also comes with some cool features that don’t exist yet in JavaScript, such as decorators.

#Uncategorized #javascript #typescript

Decorators between Class-based & Prototype-based programming languages

The difference between OOP and Prototype languages centralize around the reuse principle (Known as inheritance), its performed via a process of reusing objects (Known as prototype inheritance) in Prototype-based programming languages and via a process of reusing the classes of objects or blueprints of objects (Known as class inheritance).

The decorator is a design pattern that allows behavior to be added to an object in a dynamic way without having to change the implementation of that object. The decorator is considered as Structural design pattern. And an important note is that the decorator follows the Open-Closed Principle.

Implementing the decorator pattern will differ between Class-based and Prototype-based programming languages because of the difference in their nature. I will talk in this article about implementing the decorator pattern in both Javascript and C## programming languages. And consider some real-life scenarios to use them.


Decorator in C#

Decorators in C## can be applied using two methods:

1- Inheriting from a target class and have a setter method to set that target class instance inside the decorator or bypassing the target class as a dependency to the decorator class through the constructor. Then in the overridden functions, we call the target class function with additional decoration. The next UML explains that:

Image for post

#javascript #decorators #typescript #c-sharp-programming #decorator-pattern

Makenzie  Pagac

Makenzie Pagac

1605668648

Your Reference Guide to Using TypeScript in React

One of the issues with JavaScript is its dynamically-typed nature, meaning that data and variable types are unknown until runtime. This can have many side effects. For example, it can cause confusion within your codebase due to the fact that a variable can be anything.

To solve this issue, Microsoft released TypeScript. Anders Hejlsberg, lead architect of TypeScript, said, “What if we could strengthen JavaScript with the things that are missing for large scale application development, like static typing, classes [and] modules…? That’s what TypeScript is about.”

TypeScript instantly became the most widely used static-typed version of JavaScript. It enabled JavaScript devs to statically type data and variables. Soon enough, it was introduced to React.js, enabling React devs to write their React app in TypeScript.

But this comes at a cost: TypeScript typings and syntaxes can be difficult to keep up with, especially when used with React.

React has many features, such as props, class components, function components, function params, components lifecycle hooks, and member properties. Because typing these within TypeScript isn’t easy, this article aims to serve as a quick reference and learning guide for both beginner and advanced React devs.

With it, you’ll be able to quickly look up best practices and generic TS types in React. Ready? Let’s get started.

TypeScript typings

TypeScript has a typings folder where it saves files with *.d.ts extension. These files include interfaces that infer what shape a value will take. This is what enables TypeScript to bring data-typing to JavaScript.

An interface describes what a value would look like:

type AppState {
    propOne: number;
    propTwo: string
}

AppState describes what the value of its data-type would look like. First, we infer it would be an object that holds properties propOne and propTwo, the former being of number type and the latter being a string type. Assigning a boolean type to propOne would cause TypeScript to throw TypeError.

When we include TypeScript in our React project, every React element has an interface that defines the shape it will take. Let’s start with function component.

Function component

Function components are normal functions that return JSX elements in React and are used to create views. Initially, they are stateless components, but with the arrival of React hooks, they can be made stateful and smart/

Defining a React function component takes the React.FunctionComponent shape:

function App: React.FunctionComponent<> {
    return (
        <>
            // ...
        </>
    )
}

We can also use the shorthand React.FC:

function App: React.FC<> {
    return (
        <>
            // ...
        </>
    )
}

React.FunctionComponent, or React.FC, describes explicitly the return type of the function component.

We can type the props definitions in the arrows <>.

type AppProps = {
    message: string;
    age: number;
};

AppProps is the interface the props passed to App will take, so we can write the App component below if it would receive props:

type AppProps {
    message: string;
    age: number;
}

function App: React.FC<AppProps>(props: AppProps) {
    return (
        <>
            // ...
        </>
    )
}

We can use ? to set optional values in the typing:

type AppProps {
    message: string;
    age?: number;
}

Now, the age property becomes optional. The App component can be rendered, omitting the age property in its props object.

We can omit the type declaration within the arrows <>.

function App<{message: string; age: number;}>({message: string; age: number;}: AppProps) {
    // ...
}

Inner functions in the functional component can be typed, like so:

function App<{message: string; age: number;}>({message: string; age: number;}: AppProps) {
    // ...

    function clickHandler (val: number) {
        // ...
    }

    return (
        <>
            <button onClick={() => clickHandler(45)}            
        </>
    )
}

#typescript #typescript #javascript #web-development #developer

Idris Brhane

Idris Brhane

1612753200

Start writing your own Typescript Method Decorators

What is a Decorator?

It is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors (reference).

When we are using Typescript Method Decorators, they are higher-order functions that help us change method behavior or do something with the arguments.

Typescript method decorator definition: method decorator can be used to observe, modify, or replace a method definition (reference)

Now, let’s see how we can define a simple method decorator.

Setup

In order to run the Typescript code, we need to compile them using the Typescript compiler.

We need a tsconfig.json file :

We have to enable the experimentalDecorators. Also, the target should not be less than ES5.

If you do not want to use a tsconfig file you can pass these options directly:

tsc --experimentalDecorators // If you installed tsc globaly
npx tsc --experimentalDecorators // If you installed tsc in your current directory

Now by running tsc in the current directory, the typescript files will compile to javascript files and we can run them using Node.

#decorators #nodejs #typescript

Reid  Rohan

Reid Rohan

1617284940

Building Custom Typescript Decorators for Angular

As frontend developers we love beautiful UI. In the same vein, we really should strive to have clean reusable code. Modern tools and techniques provide us with many ways to achieve that. In this article, we will look at typescript decorators, and how they can help us add abstraction and reusability to our code.

We will do that by creating a custom decorator to launch a  Sweetalert.

But first of all let us look at what decorators are.

When I was first introduced to decorators, I wondered why we needed them at all. I mean sure, Angular uses that @Whatever symbols everywhere but how did they actually work? Ultimately they looked like black boxes. And surely, one can build apps in TS / Angular without understanding them. But once we dig a little deeper we can understand what they are, as well as the benefits of using them.

What are decorators?

At its core, a decorator is just a JavaScript function. Ok i know this sounds like a joke but really! A decorator is just a function that allows us to “extend” our code to do more. Yes it’s very abstract for now but we’ll get to clarify that soon.

Let’s look at the different types of decorators available in typescript.

There are four main types:

  • Class decorators, which are used to add functionality to a class e.g. @Component and @NgModule
  • Property decorators for adding functionality to properties inside classes, e.g. @Input and @Output
  • Method decorators for methods inside classes, e.g. @HostListener
  • Parameter decorators for parameters inside class constructors, e.g. @Inject

Each decorator has a unique role. For examples of the different decorator types and their application in angular, please check  Decorators used in Angular.

Those are the basics you should know before we can jump into the fun part, actual code :) As mentioned earlier, we will be creating a method decorator that will show a sweetalert confirmation box before a method is executed.

#custom #confirmable #angular #decorators #typescript