Posts

Showing posts from August, 2020

TypeScript - Emit Decorator Metadata - emitDecoratorMetadata

Emit Decorator Metadata - emitDecoratorMetadata Enables experimental support for emitting type metadata for decorators which works with the module reflect-metadata. For example, here is the JavaScript function LogMethod(   target: any,   propertyKey: string | symbol,   descriptor: PropertyDescriptor ) {   console.log(target);   console.log(propertyKey);   console.log(descriptor); } class Demo {   @LogMethod   public foo(bar: number) {     // do nothing   } } const demo = new Demo();Try With emitDecoratorMetadata not set to true (default): "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {     var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;     if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate...

TypeScript - (tsconfig) Linter Checks

#Linter Checks A collection of extra checks, which somewhat cross the boundaries of compiler vs linter. You may prefer to use a tool like eslint over these options if you are looking for more in-depth rules. # No Fallthrough Cases In Switch - noFallthroughCasesInSwitch Report errors for fallthrough cases in switch statements. Ensures that any non-empty case inside a switch statement includes either break or return. This means you won’t accidentally ship a case fallthrough bug. const a: number = 6; switch (a) {   case 0: Fallthrough case in switch.     console.log("even");   case 1:     console.log("odd");     break; }Try Default: false Released: 1.8 # No Implicit Returns - noImplicitReturns When enabled, TypeScript will check all code paths in a function to ensure they return a value. function lookupHeadphonesManufacturer(color: "blue" | "black"): string { Function lacks ending return statement and return type does not i...

TypeScript - (tsconfig) Source Maps

#Source Maps In order to provide rich debugging tools and crash reports which make sense to developers, TypeScript supports emitting additional files which conform to the JavaScript Source Map standards. These are emitted as .map files which live alongside the file they represent. # Inline Source Map - inlineSourceMap When set, instead of writing out a .js.map file to provide source maps, TypeScript will embed the source map content in the .js files. Although this results in larger JS files, it can be convenient in some scenarios. For example, you might want to debug JS files on a webserver that doesn’t allow .map files to be served. Mutually exclusive with sourceMap. For example, with this TypeScript: const helloWorld = "hi"; console.log(helloWorld); Converts to this JavaScript: "use strict"; const helloWorld = "hi"; console.log(helloWorld);Try Then enable building it with inlineSourceMap enabled there is a comment at the bottom of th...

TypeScript - (tsconfig) Module Resolution

#Module Resolution # Allow Synthetic Default Imports - allowSyntheticDefaultImports When set to true, allowSyntheticDefaultImports allows you to write an import like: import React from "react"; instead of: import * as React from "react"; When the module does not explicitly specify a default export. For example, without allowSyntheticDefaultImports as true: // @filename: utilFunctions.js Module '"utilFunctions"' can only be default-imported using the 'allowSyntheticDefaultImports' flag const getStringLength = (str) => str.length; module.exports = {   getStringLength, }; // @filename: index.ts import utils from "./utilFunctions"; const count = utils.getStringLength("Check JS");Try This code raises an error because there isn’t a default object which you can import. Even though it feels like it should. For convenience, transpilers like Babel will automatically create a default if one isn’t create...

TypeScript - (tsconfig) Strict Checks

#Strict Checks We recommend using the compiler option strict to opt-in to every possible improvement as they are built. TypeScript supports a wide spectrum of JavaScript patterns and defaults to allowing for quite a lot of flexibility in accommodating these styles. Often the safety and potential scalability of a codebase can be at odds with some of these techniques. Because of the variety of supported JavaScript, upgrading to a new version of TypeScript can uncover two types of errors: Errors which already exist in your codebase, which TypeScript has uncovered because the language has refined its understanding of JavaScript. A new suite of errors which tackle a new problem domain. TypeScript will usually add a compiler flag for the latter set of errors, and by default these are not enabled. # Always Strict - alwaysStrict Ensures that your files are parsed in the ECMAScript strict mode, and emit “use strict” for each source file. ECMAScript strict mode was introduced in ...

TypeScript - (tsconfig) Project Options

#Project Options These settings are used to define the runtime expectations of your project, how and where you want the JavaScript to be emitted and the level of integration you want with existing JavaScript code. # Allow JS - allowJs Allow JavaScript files to be imported inside your project, instead of just .ts and .tsx files. For example, this JS file: // @filename: card.js export const defaultCardDeck = "Heart";Try When imported into a TypeScript file will raise an error: // @filename: index.ts import { defaultCardDeck } from "./card"; console.log(defaultCardDeck);Try Imports fine with allowJs enabled: // @filename: index.ts import { defaultCardDeck } from "./card"; console.log(defaultCardDeck);Try This flag can be used as a way to incrementally add TypeScript files into JS projects by allowing the .ts and .tsx files to live along-side existing JavaScript files. Default: false Related: checkJs, emitDeclarationOnly Released: ...

TypeScript - (tsconfig) File Inclusion

#File Inclusion These settings help you ensure that TypeScript picks up the right files. # Exclude - exclude Specifies an array of filenames or patterns that should be skipped when resolving include. Important: exclude only changes which files are included as a result of the include setting. A file specified by exclude can still become part of your codebase due to an import statement in your code, a types inclusion, a /// <reference directive, or being specified in the files list. It is not a mechanism that prevents a file from being included in the codebase - it simply changes what the include setting finds. Default: ["node_modules", "bower_components", "jspm_packages"], plus the value of outDir if one is specified. Related: include, files # Extends - extends The value of extends is a string which contains a path to another configuration file to inherit from. The path may use Node.js style resolution. The configuration from the base f...

Angular Opting in to Strict Mode

Image
Angular v10 strict opt-in mode that allows to perform more build-time optimizations and help you deliver faster apps with fewer defects. This mode is still only an opt-in because it comes with its trade-offs — stricter type checking and extra configuration. Opting in to Strict Mode To opt into the strict mode, you need to create a new Angular CLI app, specifying the --strict flag: ng new my-app --strict The command above will generate a workspace with the following settings enabled on top of the defaults: Strict mode in TypeScript, as well as other strictness flags recommended by the TypeScript team. Specifically, strict, forceConsistentCasingInFileNames, noImplicitReturns, noFallthroughCasesInSwitch Turns on strict Angular compiler flags strictTemplates and strictInjectionParameters Reduced bundle size budgets by ~75% Turns on no-any TSLint rule to prevent declarations of type any Marks your application as side-effect free to enable more advanced tree-shaking Str...

Hibernate JPA @WhereJoinTable Example

@WhereJoinTable The @WhereJoinTable annotation is used to specify a custom SQL WHERE clause used when fetching a join collection table. WhereJoinTable Where clause to add to the collection join table. The clause is written in SQL. Just as with Where, a common use case is for implementing soft-deletes. @WhereJoinTable Just like @Where annotation, @WhereJoinTable is used to filter out collections using a joined table (e.g. @ManyToMany association). Example : @WhereJoinTable mapping example @Entity(name = "Book") public static class Book { @Id private Long id; private String title; private String author; @ManyToMany @JoinTable( name = "Book_Reader", joinColumns = @JoinColumn(name = "book_id"), inverseJoinColumns = @JoinColumn(name = "reader_id") ) @WhereJoinTable( clause = "created_on > DATEADD( 'DAY', -7, CURRENT_TIMESTAMP() )") private List<Reader> currentWeekReaders = new Arra...

Hibernate JPA @Where Example

@Where The @Where annotation is used to specify a custom SQL WHERE clause used when fetching an entity or a collection. Where clause to add to the element Entity or target entity of a collection. The clause is written in SQL. A common use case here is for soft-deletes. @Where mapping usage public enum AccountType { DEBIT, CREDIT } @Entity(name = "Client") public static class Client { @Id private Long id; private String name; @Where( clause = "account_type = 'DEBIT'") @OneToMany(mappedBy = "client") private List<Account> debitAccounts = new ArrayList<>( ); @Where( clause = "account_type = 'CREDIT'") @OneToMany(mappedBy = "client") private List<Account> creditAccounts = new ArrayList<>( ); //Getters and setters omitted for brevity } @Entity(name = "Account") @Where( clause = "active = true" ) public static class Account { @Id p...

Hibernate JPA @ValueGenerationType Example

@ValueGenerationType The @ValueGenerationType annotation is used to specify that the current annotation type should be used as a generator annotation type. ValueGenerationType marks an annotation type as a generator annotation type. Adding a generator annotation to an entity property causes the value of the property to be generated upon insert or update of the owning entity. Not more than one generator annotation may be placed on a given property. Each generator annotation type is associated with a AnnotationValueGeneration which implements the strategy for generating the value. Generator annotation types may define arbitrary custom attributes, e.g. allowing the client to configure the generation timing (if applicable) or other settings taking an effect on the value generation. The corresponding implementation can retrieve these settings from the annotation instance passed to AnnotationValueGeneration.initialize(java.lang.annotation.Annotation, Class). Custom generator annota...

Hibernate JPA @UpdateTimestamp Example

@UpdateTimestamp The @UpdateTimestamp annotation is used to specify that the currently annotated timestamp attribute should be updated with the current JVM timestamp whenever the owning entity gets modified. java.util.Date java.util.Calendar java.sql.Date java.sql.Time java.sql.Timestamp UpdateTimestamp marks a property as the update timestamp of the containing entity. The property value will be set to the current VM date whenever the owning entity is updated. Supported property types: Date Calendar Date Time Timestamp Instant LocalDate LocalDateTime LocalTime MonthDay OffsetDateTime OffsetTime Year YearMonth ZonedDateTime @UpdateTimestamp annotation The @UpdateTimestamp annotation instructs Hibernate to set the annotated entity attribute with the current timestamp value of the JVM when the entity is being persisted. The supported property types are: java.util.Date java.util.Calendar java.sql.Date java.sql.Time java.sql.Timestamp ...

Hibernate JPA @TypeDef Example

@TypeDef The @TypeDef annotation is used to specify a @Type definition which can later be reused for multiple basic attribute mappings. TypeDef is a type definition. Much like Type, but here we can centralize the definition under a name and refer to that name elsewhere. The plural form is TypeDefs. @TypeDef to register a custom Type @Entity(name = "Product") @TypeDef( name = "bitset", defaultForType = BitSet.class, typeClass = BitSetType.class ) public static class Product { @Id private Integer id; private BitSet bitSet; //Getters and setters are omitted for brevity } @TypeDefs The @TypeDefs annotation is used to group multiple @TypeDef annotations.

Hibernate JPA @Type Example

@Type The @Type annotation is used to specify the Hibernate @Type used by the currently annotated basic attribute. Custom BasicType mapping @Entity(name = "Product") public static class Product { @Id private Integer id; @Type( type = "bitset" ) private BitSet bitSet; public Integer getId() { return id; } //Getters and setters are omitted for brevity }