How to test if two types are exactly the same

Ah, the type-level equality operator. @MattMcCutchen has come up with a solution involving generic conditional types which does a decent job of detecting when two types are exactly equal, as opposed to just mutually assignable. In a perfectly sound type system, “mutually assignable” and “equal” would probably be the same thing, but TypeScript isn’t perfectly … Read more

Angular2 canActivate() calling async function

canActivate needs to return an Observable that completes: @Injectable() export class AuthGuard implements CanActivate { constructor(private auth: AngularFireAuth, private router: Router) {} canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean>|boolean { return this.auth.map((auth) => { if (auth) { console.log(‘authenticated’); return true; } console.log(‘not authenticated’); this.router.navigateByUrl(‘/login’); return false; }).first(); // this might not be necessary – ensure `first` is imported if you … Read more

Typescript primitive types: any difference between the types “number” and “Number” (is TSC case-insensitive)?

To augment Ryan’s answer with guidance from the TypeScript Do’s and Don’ts: Don’t ever use the types Number, String, Boolean, Symbol, or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code. /* WRONG */ function reverse(s: String): String; Do use the types number, string, boolean, and symbol. … Read more

How to prepare release version with SystemJS and Gulp?

You will get ” Unexpected anonymous System.register call” because the references are not being loaded in the correct order. I use JSPM to properly build my angular app for production. There are 4 parts to the process. Part 1: Compile your typescript files var ts = require(“gulp-typescript”); var tsProject = ts.createProject(“./App/tsconfig.json”); gulp.task(“compile:ts”, function () { … Read more

How to use fetch in TypeScript

A few examples follow, going from basic through to adding transformations after the request and/or error handling: Basic: // Implementation code where T is the returned data shape function api<T>(url: string): Promise<T> { return fetch(url) .then(response => { if (!response.ok) { throw new Error(response.statusText) } return response.json<T>() }) } // Consumer api<{ title: string; message: … Read more

Typescript check object by type or interface at runtime with typeguards in 2020+

There are actually a number of modules which attempt to translate TypeScript type information into runtime information that can be used to validate data structures. I’ll attempt to list and compare the various solutions here. (ordered roughly by how effective/general-purpose I estimate them to be; yes, this is somewhat subjective!) Core features: (marked with ✔️yes, … Read more