Narrowing a return type from a generic, discriminated union in TypeScript

Like many good solutions in programming, you achieve this by adding a layer of indirection. Specifically, what we can do here is add a table between action tags (i.e. “Example” and “Another”) and their respective payloads. type ActionPayloadTable = { “Example”: { example: true }, “Another”: { another: true }, } then what we can … Read more

How do I decide whether @types/* goes into `dependencies` or `devDependencies`?

Let’s say you’re developing a package “A” that have @types/some-module package in devDependencies. For some reason you’re exporting the type from @types/some-module: import { SomeType } from ‘some-module’; export default class APackageClass { constructor(private config: SomeType) { // … } } Right now TypeScript consumers of package “A” are unable to guess what SomeType is, … Read more

typings vs @types NPM scope

@types is the new way to install the definitions in typescript 2.0. It unifies the management of definitions and packages. So that you do not need multiple tools and config files. Only going to need npm and package.json instead of having to have npm, package.json, typings, typings.json. It basically makes installing and managing definitions easier … Read more

Typescript Unions based on property inside nested object

The compiler doesn’t understand the concept of “nested discriminated unions”. A type is a discriminated union if the members of the union share a common “discriminant” property. A discriminant property is generally a singleton/literal type like true or “hello” or 123 or even null or undefined. You can’t use another discriminated union as a discriminant … Read more

Global types in typescript

Yes this is possible. You can find all information here: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html The important part is this: declare global { /*~ Here, declare things that go in the global namespace, or augment *~ existing declarations in the global namespace */ interface String { fancyFormat(opts: StringFormatOptions): string; } }

Angular 4+ using Google Analytics

First of all, you need to install typings for Google Analytics in your devDependencies npm install –save-dev @types/google.analytics Then add your tracking code in the base index.html, and remove the last line as shown bellow: <body> <app-root>Loading…</app-root> <script> (function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,’script’,’https://www.google-analytics.com/analytics.js’,’ga’); ga(‘create’, ‘UA-XXXXXX-ID’, ‘auto’); // <- add the UA-ID // <- remove the … Read more